QTimer example for PyQt5
If an operation is performed periodically in the application, such as periodically detecting the CPU value of the host, then the QTimer
timer is needed.
When the window’s control receives a Timeout signal, it stops this timer.
QTimer has the method start(milliseconds)
and Stop()
.
Book: Create Desktop Apps with Python PyQt5
QTimer example
The program below has a start and stop button. If you click the start button, it starts a QTimer
.

This will update the time every second.
import sys
from PyQt5.QtWidgets import QWidget,QPushButton,QApplication,QListWidget,QGridLayout,QLabel
from PyQt5.QtCore import QTimer,QDateTime
class WinForm(QWidget):
def __init__(self,parent=None):
super(WinForm, self).__init__(parent)
self.setWindowTitle('QTimer example')
self.listFile=QListWidget()
self.label=QLabel('Label')
self.startBtn=QPushButton('Start')
self.endBtn=QPushButton('Stop')
layout=QGridLayout()
self.timer=QTimer()
self.timer.timeout.connect(self.showTime)
layout.addWidget(self.label,0,0,1,2)
layout.addWidget(self.startBtn,1,0)
layout.addWidget(self.endBtn,1,1)
self.startBtn.clicked.connect(self.startTimer)
self.endBtn.clicked.connect(self.endTimer)
self.setLayout(layout)
def showTime(self):
time=QDateTime.currentDateTime()
timeDisplay=time.toString('yyyy-MM-dd hh:mm:ss dddd')
self.label.setText(timeDisplay)
def startTimer(self):
self.timer.start(1000)
self.startBtn.setEnabled(False)
self.endBtn.setEnabled(True)
def endTimer(self):
self.timer.stop()
self.startBtn.setEnabled(True)
self.endBtn.setEnabled(False)
if __name__ == '__main__':
app=QApplication(sys.argv)
form=WinForm()
form.show()
sys.exit(app.exec_())
First initialize a timer and connect the timer’s timeout signal to the showTime() slot function
self.timer=QTimer(self)
self.timer.timeout.connect(self.showTime)
Use the connected slot function to display the current time, with the system’s current time on the label
def showTime(self):
#get system current time
time=QDateTime.currentDateTime()
#Setting the display format for system time
timeDisplay=time.toString('yyyy-MM-dd hh:mm:ss dddd')
#Show time on the label.
self.label.setText(timeDisplay)
Click the Start button to start the timer and disable the button
#Set the interval and start the timer.
self.timer.start(1000)
#Set Start button unclickable, End button clickable
self.startBtn.setEnabled(False)
self.endBtn.setEnabled(True)
Click the end button to stop the timer and disable the button
#Stop the timer.
self.timer.stop()
#End button is not clickable, start button is clickable
self.startBtn.setEnabled(True)
self.endBtn.setEnabled(False)