PyQt5 为 QPushButton 实现长按和解决跟 clicked 事件的冲突

from PyQt5.QtWidgets import QPushButton
from PyQt5.QtGui import QMouseEvent
from PyQt5.QtCore import QTimer, pyqtSignal

class PushButton(QPushButton):
    long_pressed = pyqtSignal()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.timer = QTimer()
        self.timer.timeout.connect(self._long_pressed)

    def mousePressEvent(self, evt: QMouseEvent):
        super().mousePressEvent(evt)
        self.timer.start(1000)

    def mouseReleaseEvent(self, evt: QMouseEvent):
        # 长按后此方法仍会触发 clicked 事件,需要禁止信号发射。
        if self.timer.remainingTime() <= 0:
            self.blockSignals(True)
        self.timer.stop()
        super().mouseReleaseEvent(evt)
        self.blockSignals(False)

    def _long_pressed(self):
        self.timer.stop()
        self.long_pressed.emit()
本作品采用《CC 协议》,转载必须注明作者和本文链接
一代咩神
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!