PyQt5单发定时器:使用singleShot()方法进行一次性定时任务调度
发布时间:2024-01-01 03:36:48
PyQt5中的QTimer类提供了定时器功能,可以用来实现定时执行任务的功能。其中,singleShot()方法可以用来执行一次性的定时任务。
singleShot()方法的语法如下:
QTimer.singleShot(msec, slot)
该方法接受两个参数:
- msec:以毫秒为单位的定时时间。即在多久之后执行任务。
- slot:要执行的任务,即槽函数。
下面给出一个使用singleShot()方法的例子,该例子包括一个按钮和一个标签。按钮点击后,会启动一个定时器,3秒后标签的文本会改变。
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QVBoxLayout, QWidget
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.label = QLabel("定时任务还未触发", self)
self.button = QPushButton("启动定时器", self)
self.button.clicked.connect(self.startTimer)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
def startTimer(self):
self.label.setText("定时任务已启动")
QTimer.singleShot(3000, self.updateLabel)
def updateLabel(self):
self.label.setText("定时任务已触发")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
上述代码首先创建了一个继承自 QWidget 的 Example 类,然后在 initUI() 方法中创建了一个 QLabel 和一个 QPushButton。按钮被点击时会调用 startTimer() 方法。在 startTimer() 方法中,首先将标签的文本设置为 "定时任务已启动",然后使用 QTimer.singleShot() 方法启动定时器。定时器在 3 秒后会触发 updateLabel() 方法。updateLabel() 方法会将标签的文本设置为 "定时任务已触发"。
