以下是一个使用PyQt库的示例代码,实现按住鼠标按钮10秒后连接信号的功能:
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtGui import QMouseEvent
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(300, 300)
self.mouse_pressed = False
self.timer = QTimer()
self.timer.timeout.connect(self.check_button_held)
def mousePressEvent(self, event: QMouseEvent):
if event.button() == Qt.LeftButton:
self.mouse_pressed = True
self.timer.start(10000) # 10秒后触发timeout信号
def mouseReleaseEvent(self, event: QMouseEvent):
if event.button() == Qt.LeftButton:
self.mouse_pressed = False
self.timer.stop()
def check_button_held(self):
if self.mouse_pressed:
print("连接信号")
self.timer.stop()
if __name__ == '__main__':
app = QApplication([])
widget = MyWidget()
widget.show()
app.exec_()
这个示例创建了一个继承自QWidget的自定义窗口类MyWidget。通过重写mousePressEvent和mouseReleaseEvent方法来监听鼠标按下和释放事件。当鼠标左键按下时,设置mouse_pressed为True,并启动一个定时器,10秒后触发timeout信号。当鼠标左键释放时,设置mouse_pressed为False,并停止定时器。在check_button_held方法中,检查mouse_pressed的值,如果为True,则打印"连接信号",并停止定时器。
通过运行上述代码,当你按住鼠标左键10秒钟后,会在控制台打印"连接信号"。