当前位置:   article > 正文

[Python] pyqt6 - QTimer定时器介绍和使用场景(案例)_python qtimer

python qtimer

QTimer定时器介绍

PyQt6中的QTimer是一个定时器类,用于在指定的时间间隔内执行某个操作。QTimer提供了一种简单的方法来实现定时任务,例如自动更新界面、动画效果等。

函数原型:

  1. from PyQt6.QtCore import QTimer
  2. QTimer()

创建一个QTimer对象:

timer = QTimer()

设置定时器的超时时间(毫秒):

timer.setInterval(1000)  # 设置为1000毫秒(1秒)

连接定时器的超时信号到槽函数:

  1. def on_timeout():
  2. print("定时器超时")
  3. timer.timeout.connect(on_timeout)

启动定时器:

timer.start()

停止定时器:

timer.stop()

使用案例

每隔1秒更新界面上的文本

  1. from PyQt6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
  2. from PyQt6.QtCore import QTimer
  3. import sys
  4. class MyApp(QWidget):
  5. def __init__(self):
  6. super().__init__()
  7. self.label = QLabel("Hello, World!")
  8. layout = QVBoxLayout()
  9. layout.addWidget(self.label)
  10. self.setLayout(layout)
  11. self.timer = QTimer()
  12. self.timer.timeout.connect(self.update_text)
  13. self.timer.start(1000) # 每隔1秒触发一次timeout信号
  14. self.cnt = 1
  15. def update_text(self):
  16. self.label.setText(f"Hello, PyQt6! cnt:{self.cnt}")
  17. self.cnt = self.cnt + 1
  18. app = QApplication(sys.argv)
  19. window = MyApp()
  20. window.show()
  21. sys.exit(app.exec())

代码中使用了QTimer类来实现定时器功能。首先,创建了一个MyApp类,继承自QWidget类。在MyApp类的构造函数中,创建了一个QLabel对象和一个QVBoxLayout对象,并将它们添加到布局中。然后,创建了一个QTimer对象,并将其timeout信号连接到update_text槽函数。最后,启动了定时器,并设置了时间间隔为1000毫秒(即1秒)。

在update_text槽函数中,更新了QLabel对象的文本,并将计数器cnt加1。这样,每次调用update_text函数时,都会更新窗口中的文本,并使计数器cnt递增。

最后,创建了一个QApplication对象和一个MyApp对象,并将MyApp对象显示出来。程序运行结束后,退出应用程序。

10秒后显示一个消息框 

  1. import sys
  2. from PyQt6.QtWidgets import QApplication, QWidget, QMessageBox
  3. from PyQt6.QtCore import QTimer
  4. class Example(QWidget):
  5. def __init__(self):
  6. super().__init__()
  7. self.setGeometry(300, 300, 250, 150)
  8. self.setWindowTitle('QTimer')
  9. self.show()
  10. # 创建一个QTimer对象
  11. self.timer = QTimer()
  12. # 将timeout信号连接到自定义的槽函数
  13. self.timer.timeout.connect(self.on_timeout)
  14. # 设置定时器的时间间隔为10000毫秒(10秒)
  15. self.timer.setInterval(10000)
  16. self.timer.start()
  17. def on_timeout(self):
  18. # 当定时器超时时,显示一个消息框
  19. QMessageBox.information(self, 'Timeout', '10秒已过!')
  20. self.timer.stop()
  21. if __name__ == '__main__':
  22. app = QApplication(sys.argv)
  23. ex = Example()
  24. sys.exit(app.exec())

在这个示例中,我们首先导入了所需的库,并创建了一个名为Example的QWidget子类。在initUI方法中,我们设置了窗口的大小、标题和位置,并创建了一个QTimer对象。然后,我们将QTimer的timeout信号连接到自定义的on_timeout槽函数,并设置定时器的时间间隔为10000毫秒(10秒)。最后,我们在on_timeout槽函数中显示一个消息框,通知用户已经过了10秒,并停止定时器。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/793680
推荐阅读
相关标签
  

闽ICP备14008679号