PyQt5 為 QPushButton 實現長按及解決跟 clicked 事件的衝突

一代咩神發表於2021-05-06
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 協議》,轉載必須註明作者和本文連結

相關文章