python QTimer
时间: 2025-04-23 18:40:13 浏览: 39
### 使用 `QTimer` 实现定时任务
在 Python 中,通过 PyQt 库可以方便地使用 `QTimer` 来创建定时器对象并安排周期性的调用。这适用于各种应用场景,比如刷新数据、处理动画或是管理超时机制。
#### 创建简单的单次触发定时器
下面展示了一个例子,在该实例中程序启动一个无边框的消息提示窗口,并设定五秒钟之后关闭此窗口[^4]:
```python
import sys
from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtCore import Qt, QTimer
if __name__ == "__main__":
application = QApplication(sys.argv)
message_label = QLabel('<font color=blue size=20><b>PyQt5,窗口5秒后消失</b></font>')
# 设置为无边框样式
message_label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
message_label.show()
# 单次触发的定时器,延迟时间为5000毫秒即5秒
QTimer.singleShot(5000, application.quit)
sys.exit(application.exec_())
```
这段代码展示了如何利用 `singleShot()` 方法来设置一次性延时操作;当达到预设的时间长度(这里是5秒),就会执行传入的方法——这里是指令应用程序结束运行。
#### 构建重复触发的任务调度
对于需要反复执行的操作,则可以通过连接信号槽的方式实现更复杂的功能逻辑。例如每隔一秒打印当前时间到控制台[^1]:
```python
import sys
from datetime import datetime
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QTextEdit
class TimePrinter(QTextEdit):
def __init__(self):
super().__init__()
self.timer = QTimer(self)
self.timer.timeout.connect(self.print_time)
self.timer.start(1000) # 每隔1000ms也就是每秒触发一次
def print_time(self):
current_time = str(datetime.now().time())[:8]
self.append(f'现在时刻: {current_time}')
def main():
app = QApplication([])
time_printer_widget = TimePrinter()
time_printer_widget.setWindowTitle('实时显示时间')
time_printer_widget.resize(300, 200)
time_printer_widget.show()
app.exec_()
if __name__ == '__main__':
main()
```
在这个案例里定义了一个继承自 `QTextEdit` 的新组件类 `TimePrinter` ,内部包含了初始化函数以及用来响应计时器溢出事件的方法 `print_time()` 。每当定时器到达其间隔期满的时候便会激活这个方法从而完成相应动作。
阅读全文
相关推荐















