gpt4 book ai didi

python - QTabWidget 的 PyQt 鼠标事件

转载 作者:太空狗 更新时间:2023-10-30 00:51:40 27 4
gpt4 key购买 nike

我想检测 QTabWidget 上的鼠标中键点击。我原以为 QWidget 上会有与鼠标事件相关的信号,但我看到的只是方法。

我是否需要对 QTabWidget 进行子类化,然后重写所述方法才能执行我想做的事情,还是我遗漏了什么?

最佳答案

您可以在 QTabBar 上安装事件过滤器(由 QTabWidget.tabBar() 返回)来接收和处理按下和释放事件,或者子类 QTabBar 重新定义mousePressEventmouseReleaseEvent,将QTabWidgetQTabBar替换为QTabWidget .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

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

关于python - QTabWidget 的 PyQt 鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9442165/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com