I cannot repro your second question. Items are added properly into the QMenu on my site. For your second question, because you put the "addAction" (2 of the default items) under the "_showContextMenu" , so theyare added when you right clicking the tab.
To be noticed, I am using Pyside2, so I placed all the QtGui to QtWidgets.
from PySide2 import QtWidgets
from PySide2 import QtCore
class TabBar(QtWidgets.QTabBar ):
def __init__(self, parent=None):
super(TabBar, self).__init__(parent)
self.qmenu = QtWidgets.QMenu()
self.setExpanding(False)
add_item_action = QtWidgets.QAction('Add new item', self,
triggered=self.add_new_item)
self.qmenu.addAction(add_item_action)
self.qmenu.addSeparator()
def_item_01 = self.qmenu.addAction("Default Item A")
def_item_02 = self.qmenu.addAction("Default Item B")
self.separator = self.qmenu.addSeparator()
def tabSizeHint(self, index):
return super(TabBar, self).tabSizeHint(index)
def mousePressEvent(self, event):
index = self.tabAt(event.pos())
if event.button() == QtCore.Qt.RightButton:
self._showContextMenu(event.pos(), index)
else:
super(TabBar, self).mousePressEvent(event)
def _showContextMenu(self, position, index):
# Default items
global_position = self.mapToGlobal(self.pos())
self.qmenu.exec_(QtCore.QPoint(
global_position.x() - self.pos().x() + position.x(),
global_position.y() - self.pos().y() + position.y()
))
@QtCore.Slot()
def add_new_item(self):
new_item_name, ok = QtWidgets.QInputDialog.getText(
self,
"name of item",
"Name of new item : "
)
if ok:
new_action = QtWidgets.QAction(new_item_name, self.qmenu, checkable=True)
self.qmenu.insertAction(self.separator, new_action)
class TabWidget(QtWidgets.QTabWidget):
def __init__(self, parent=None):
super(TabWidget, self).__init__(parent)
self.setTabBar(TabBar(self))
def resizeEvent(self, event):
self.tabBar().setMinimumWidth(self.width())
super(TabWidget, self).resizeEvent(event)
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.tabs = TabWidget(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
some_tabs = ['TabA', 'TabB', 'TabC', 'TabD']
for my_tab in some_tabs:
self.tabs.addTab(QtWidgets.QWidget(self), my_tab)
test = Window()
test.show()
Sr. Technical Artist