How to use Timer in PyQt5 to achieve timed tasks?

The steps to implement a timing task using QTimer in PyQt5 are as follows:

  1. Import the necessary modules.
from PyQt5.QtCore import QTimer
  1. a timer in Qt
timer = QTimer()
timer.setInterval(1000)  # 设置定时任务的时间间隔为1秒
  1. Connect the slot function triggered by the scheduled task.
def update():
    print("定时任务触发")

timer.timeout.connect(update)
  1. Start the scheduled task.
timer.start()

Here is the complete example code:

from PyQt5.QtCore import QTimer

def update():
    print("定时任务触发")

timer = QTimer()
timer.setInterval(1000)
timer.timeout.connect(update)
timer.start()

import sys
from PyQt5.QtWidgets import QApplication, QWidget

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    window.setWindowTitle('定时任务示例')
    window.show()
    sys.exit(app.exec_())

The above is the method of implementing timed tasks using QTimer, which can adjust the time interval of the task and the operation executed according to actual needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds