5

我想检测 QTabWidget 上的鼠标中键点击。我期待在 QWidget 上有一个与鼠标事件相关的信号,但我所看到的只是方法。

我是否需要对 QTabWidget 进行子类化,然后重写所述方法以执行我想要的操作,或者我是否遗漏了什么?

4

1 回答 1

8

您可以在QTabBar(返回QTabWidget.tabBar()) 上安装一个事件过滤器来接收和处理按下和释放事件,或者子类来QTabBar重新定义mousePressEventmouseReleaseEvent替换QTabBarQTabWidgetQTabWidget.setTabBar()

  1. 使用事件过滤器的示例:

    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
    
        # function called with the index of the clicked Tab
        def onTabMiddleClick(self, index):
            pass
    
  2. 使用 QTabBar 子类的示例:

    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
    

(如果你想知道为什么这么简单的任务有这么多代码,点击被定义为按下事件,然后在大致相同的位置释放事件,所以按下的选项卡的索引必须与已发布标签)。

于 2012-02-25T16:01:20.033 回答