PyQt5.QtCore.QTimer定时器的单次触发与多次触发比较
发布时间:2024-01-02 08:11:48
在PyQt5中,可以使用QTimer定时器来实现定时触发事件的功能。QTimer是QtCore模块中的一个类,用于创建定时器对象。
QTimer类中有两个方法用于设置定时器的触发方式:
- singleShot(msec, slot):将定时器设置为单次触发模式。在指定的时间间隔后触发指定的slot。
- start(msec):将定时器设置为多次触发模式。在指定的时间间隔后以及每次定时间隔后触发定时器的timeout信号。
下面是一个使用QTimer的例子,分别演示了单次触发和多次触发的用法。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtCore import QTimer
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("QTimer Example")
self.button_single = QPushButton("Single Shot", self)
self.button_single.move(100, 50)
self.button_single.clicked.connect(self.single_shot)
self.button_multi = QPushButton("Multiple Shots", self)
self.button_multi.move(100, 100)
self.button_multi.clicked.connect(self.multi_shots)
def single_shot(self):
self.timer = QTimer()
self.timer.timeout.connect(self.timer_timeout)
self.timer.singleShot(2000, self.timer_timeout)
self.timer.start()
def multi_shots(self):
self.timer = QTimer()
self.timer.timeout.connect(self.timer_timeout)
self.timer.start(1000)
def timer_timeout(self):
print("Timer timeout.")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
在这个例子中,我们创建了一个简单的窗口应用程序,窗口中有两个按钮:Single Shot和Multiple Shots。当单击Single Shot按钮时,使用singleShot方法创建一个单次触发的定时器,它将在2秒后触发timer_timeout函数。当单击Multiple Shots按钮时,使用start方法创建一个多次触发的定时器,它将在1秒后触发 次,然后每隔1秒再触发一次。
timer_timeout函数被定时器的timeout信号连接着,每次定时器触发时都会执行这个函数,并打印出"Timer timeout."。
运行程序,单击Single Shot按钮后,2秒钟后会打印出"Timer timeout.",而单击Multiple Shots按钮后,每隔1秒会打印一次"Timer timeout."。
总结:
- singleShot方法用于设置单次触发的定时器,参数msec表示触发时间间隔。
- start方法用于设置多次触发的定时器,参数msec表示触发时间间隔。
- 在连接定时器的timeout信号时,指定的槽函数会在定时器触发时执行。
