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() |
PyQt5 为 QPushButton 实现长按和解决跟 clicked 事件的冲突
Python
523
0
0
2022-04-11