You can set an event filter in QTabBar (returned by QTabWidget.tabBar() ) to receive and handle click and release events or subclass QTabBar to override mousePressEvent and mouseReleaseEvent and replace QTabBar QTabWidget with QTabWidget.setTabBar() .
An example of using an event filter:
class MainWindow(QMainWindow): def __init__(self): super(QMainWindow,self).__init__() self.tabWidget = QTabWidget(self) self.setCentralWidget(self.tabWidget) self.tabWidget.tabBar().installEventFilter(self) self.tabWidget.tabBar().previousMiddleIndex = -1 def eventFilter(self, object, event): if object == self.tabWidget.tabBar() and \ event.type() in [QEvent.MouseButtonPress, QEvent.MouseButtonRelease] and \ event.button() == Qt.MidButton: tabIndex = object.tabAt(event.pos()) if event.type() == QEvent.MouseButtonPress: object.previousMiddleIndex = tabIndex else: if tabIndex != -1 and tabIndex == object.previousMiddleIndex: self.onTabMiddleClick(tabIndex) object.previousMiddleIndex = -1 return True return False
An example of using the QTabBar subclass:
class TabBar(QTabBar): middleClicked = pyqtSignal(int) def __init__(self): super(QTabBar, self).__init__() self.previousMiddleIndex = -1 def mousePressEvent(self, mouseEvent): if mouseEvent.button() == Qt.MidButton: self.previousIndex = self.tabAt(mouseEvent.pos()) QTabBar.mousePressEvent(self, mouseEvent) def mouseReleaseEvent(self, mouseEvent): if mouseEvent.button() == Qt.MidButton and \ self.previousIndex == self.tabAt(mouseEvent.pos()): self.middleClicked.emit(self.previousIndex) self.previousIndex = -1 QTabBar.mouseReleaseEvent(self, mouseEvent) class MainWindow(QMainWindow): def __init__(self): super(QMainWindow,self).__init__() self.tabWidget = QTabWidget(self) self.setCentralWidget(self.tabWidget) self.tabBar = TabBar() self.tabWidget.setTabBar(self.tabBar) self.tabBar.middleClicked.connect(self.onTabMiddleClick) # function called with the index of the clicked Tab def onTabMiddleClick(self, index): pass
(In case you are wondering why there is so much code for such a simple task, a click is defined as a press event, followed by a release event in approximately the same place, so the index of the pressed tab should be the same as the released tab )
source share