如何用事件过滤器读取双击?

2 投票
1 回答
2324 浏览
提问于 2025-04-18 16:34

我在我的自定义标签上设置了一个事件过滤器,我想用它来捕捉双击事件。这可能吗?

    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

1 个回答

2

是的,这确实是可能的,但出于某种奇怪的原因,这并不是那么简单。你永远不知道一次点击后,可能会紧接着再来一次点击,这样就会变成双击。因此,系统里必须有一个内置的等待时间。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_()

另外,你可以查看 在Qt中区分单击和双击事件

撰写回答