如何阅读双击事件过滤器?

2024-04-24 10:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我的自定义标签上有一个eventFilter,我想用它嗅出双击。这可能吗?在

    self.installEventFilter(self)

# Handles mouse events
def eventFilter(self, object, event):

    try:
        if event.buttons() == QtCore.Qt.LeftButton:

            #LeftButton event

        else:
            # nothing is being pressed
    except:
        pass

Tags: selfeventifobjectdef标签eventshandles
1条回答
网友
1楼 · 发布于 2024-04-24 10:19:40

是的,这是可能的,但由于某些奇怪的原因,这并不是那么简单。当然,你永远不知道一次单击之后是否会出现另一次有效的双击。这就是为什么必须有一些内在的等待时间。Qt执行此操作并传递双击事件(QEvent.MouseButtonDblClick)。另一方面,Qt仍然为单次单击(QEvent.MouseButtonPress)提供事件,即使是在双击的情况下,但是只有一次。这可能不是最好的设计。在

我们必须正确区分它们。我用一个额外的定时器来做,它需要比内置的Qt定时器长一点来检测双击。然后代码是:

from PySide import QtCore, QtGui

class MyLabel(QtGui.QLabel):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.installEventFilter(self)
        self.single_click_timer = QtCore.QTimer()
        self.single_click_timer.setInterval(200)
        self.single_click_timer.timeout.connect(self.single_click)

    def single_click(self):
        self.single_click_timer.stop()
        print('timeout, must be single click')

    def eventFilter(self, object, event):
        if event.type() == QtCore.QEvent.MouseButtonPress:
            self.single_click_timer.start()
            return True
        elif event.type() == QtCore.QEvent.MouseButtonDblClick:
            self.single_click_timer.stop()
            print('double click')
            return True

        return False


app = QtGui.QApplication([])

window = MyLabel('Click me')
window.resize(200, 200)
window.show()

app.exec_()

另请参见Distinguish between single and double click events in Qt。在

相关问题 更多 >