PyQt5: QPushButton double click?

╄→尐↘猪︶ㄣ 提交于 2021-02-04 21:22:14

问题


I can't find a good answer for this: is there a way for double click to execute a certain function, and single click one other function?? For example:

def func1(self):
    print('First function')
def func2(self):
    print('Second function')
self.ui.button.clicked.connect(self.func1)
self.ui.button.doubleClicked.connect(self.func2)

I've seen double clicking is possible for the QTreeview but not a QPushButton. Thanks!


回答1:


You can add the functionality easily yourself by extending QPushButton class:

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class QDoublePushButton(QPushButton):
    doubleClicked = pyqtSignal()
    clicked = pyqtSignal()

    def __init__(self, *args, **kwargs):
        QPushButton.__init__(self, *args, **kwargs)
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.clicked.emit)
        super().clicked.connect(self.checkDoubleClick)

    @pyqtSlot()
    def checkDoubleClick(self):
        if self.timer.isActive():
            self.doubleClicked.emit()
            self.timer.stop()
        else:
            self.timer.start(250)

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.button = QDoublePushButton("Test", self)
        self.button.clicked.connect(self.on_click)
        self.button.doubleClicked.connect(self.on_doubleclick)

        self.layout = QHBoxLayout()
        self.layout.addWidget(self.button)

        self.setLayout(self.layout)
        self.resize(120, 50)
        self.show()

    @pyqtSlot() 
    def on_click(self):
        print("Click")

    @pyqtSlot()
    def on_doubleclick(self):
        print("Doubleclick")

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

However, I would not recommend it. Users do not expect to double-click buttons. You can refer to Command Buttons Microsoft guidelines.



来源:https://stackoverflow.com/questions/25987166/pyqt5-qpushbutton-double-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!