How to use Timer in PyQt5 to achieve timed tasks?
The steps to implement a timing task using QTimer in PyQt5 are as follows:
- Import the necessary modules.
from PyQt5.QtCore import QTimer
- a timer in Qt
timer = QTimer()
timer.setInterval(1000) # 设置定时任务的时间间隔为1秒
- Connect the slot function triggered by the scheduled task.
def update():
print("定时任务触发")
timer.timeout.connect(update)
- 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.