Hi all, I am trying to grab ahold of the mouse position + right mouse click on QTabBar where it will pops up a message to User if they want to remove the said tab.
(Pardon the vague design) This is what my QTabBar looks like:
| + | food | snacks | drinks |
However, in my following code, whenever I tried to print out the index as I do a right-mouse click on the tabs, the returned index value is wrong.
It seems to have taken into account of the ‘+’ button as it is indicating as index 0 where index 0 should actually starts from the ‘food’ tab onwards.
Here is my code:
class MyWin(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyWin, self).__init__()
central_widget = QtGui.QWidget()
self.setCentralWidget(central_widget)
vlay = QtGui.QVBoxLayout(central_widget)
hlay = QtGui.QHBoxLayout()
vlay.addLayout(hlay)
vlay.addStretch()
self.add_button = QtGui.QToolButton()
self.tab_bar = QtGui.QTabBar(self)
self.add_button.setIcon(QtGui.QIcon('add.png'))
self.add_button.setMenu(self.set_menu())
self.add_button.setPopupMode(QtGui.QToolButton.InstantPopup)
self.tab_bar.setTabButton(
0,
QtGui.QTabBar.ButtonPosition.RightSide,
self.add_button
)
hlay.addWidget(self.add_button)
hlay.addWidget(self.tab_bar)
def set_menu(self):
menu_options = ['food', 'drinks', 'snacks']
qmenu = QtGui.QMenu(self.add_button)
for opt in menu_options:
qmenu.addAction(opt, partial(self.set_new_tab, opt))
qmenu.addAction
return qmenu
def set_new_tab(self, opt):
self.tab_bar.addTab(opt)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.RightButton:
index = self.tab_bar.tabAt(event.pos())
print index
else:
super(MyWin, self).mousePressEvent(event)
my_win = MyWin()
my_win.show()
Appreciate for any insights and many thanks in advance for any response!