欢迎访问宙启技术站
智能推送

使用PyQt5的singleShot()方法实现一次性定时器

发布时间:2024-01-01 03:33:51

PyQt5的singleShot()方法用于创建一个一次性的定时器,即只会触发一次的定时器。它的语法如下:

QTimer.singleShot(msecs, slot)

其中,msecs是定时器的触发时间(单位为毫秒),slot是定时器触发时要执行的槽函数。

下面是一个使用PyQt5的singleShot()方法实现一次性定时器的例子:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtCore import QTimer

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.initUI()
    
    def initUI(self):
        self.setWindowTitle("One-shot Timer Example")
        
        self.label = QLabel(self)
        self.label.setText("Timer is not started")
        self.label.setGeometry(50, 50, 200, 30)
        
        self.startTimerButton = QPushButton(self)
        self.startTimerButton.setText("Start Timer")
        self.startTimerButton.setGeometry(50, 100, 100, 30)
        self.startTimerButton.clicked.connect(self.startTimer)
        
        self.show()
    
    def startTimer(self):
        self.label.setText("Timer is started")
        
        QTimer.singleShot(5000, self.timerExpired)
    
    def timerExpired(self):
        self.label.setText("Timer is expired")
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    sys.exit(app.exec_())

上述代码创建了一个继承自QMainWindow的主窗口类MainWindow。在主窗口中,我们添加了一个标签(用于显示定时器的状态)和一个按钮。点击按钮会启动一个定时器,定时器的触发时间设置为5秒(5000毫秒),并且在定时器触发后会调用槽函数timerExpired(),更新标签的显示内容。

在if __name__ == "__main__"的部分,我们创建了一个QApplication实例,并且创建了MainWindow实例,最后进入主循环。

运行上述代码,会打开一个主窗口,在窗口中有一个标签和一个按钮。当点击按钮后,标签会显示 "Timer is started",然后5秒后会显示 "Timer is expired"。

注意:由于定时器是一次性的,所以只会在一定的时间后触发一次,不会重复触发。