Skip to main content
 首页 » 编程设计

python之在pyside中区分单击和双击

2025年05月04日10think

我尝试在 Pyside 中实现 How to distinguish between mouseReleaseEvent and mousedoubleClickEvent on QGrapnhicsScene 中描述的方法,但我不得不添加一个笨拙的标志,以防止它在双击释放第二个按钮后显示单击。

有没有更好的办法?

import sys 
from PySide import QtGui, QtCore 
 
class Example(QtGui.QWidget): 
 
    def __init__(self): 
        super(Example, self).__init__() 
        """an attempt to implement  
        https://stackoverflow.com/questions/18021691/how-to-distinguish-between-mousereleaseevent-and-mousedoubleclickevent-on-qgrapn 
        main() 
            connect(timer, SIGNAL(timeout()), this, SLOT(singleClick())); 
        mouseReleaseEvent() 
            timer->start(); 
        mouseDoubleClickEvent() 
            timer->stop(); 
        singleClick() 
            // Do single click behavior 
        """ 
        self.timer = QtCore.QTimer() 
        self.timer.setSingleShot(True) 
        # had to add a "double_clicked" flag 
        self.double_clicked = False 
        self.timer.timeout.connect(self.singleClick) 
 
        self.setGeometry(300, 300, 250, 150) 
        self.setWindowTitle('Single click, double click')     
        self.show() 
 
    def mouseReleaseEvent(self, event): 
        if not self.double_clicked: 
            self.timer.start(200) 
        else: 
            self.double_clicked = False 
 
    def mouseDoubleClickEvent(self, event): 
        self.timer.stop() 
        self.double_clicked = True 
        print 'double click' 
 
    def singleClick(self): 
        print 'singleClick' 
 
if __name__ == '__main__': 
    app = QtGui.QApplication(sys.argv) 
    ex = Example() 
    sys.exit(app.exec_()) 

请您参考如下方法:

好吧,正如您所发现的,原始描述是不完整的。

它提供了区分双击和单击的第一次点击,而不是双击和单击的第二次点击的解决方案-点击。

区分第二次点击的最简单的解决方案是使用标志。

PS:您可以使用 QtGui.qApp.doubleClickInterval 稍微改进您的示例用于定时器间隔。