RkBlog

Hardware, programming and astronomy tutorials and reviews.

QTimer - making timers in PyQt4

Description of timers available in PyQt4

QTimer class allows applications to do something after certain amount of time. You can make constant timers that run forever, or singleShot timers that run only once. Both timers are shown in this example:
# -*- coding: utf-8 -*-
import sys

from PyQt4 import QtCore, QtGui
from timer import Ui_MainWindow

class timers(QtGui.QMainWindow):
	def __init__(self, parent=None):
		super(timers, self).__init__(parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.ctimer = QtCore.QTimer()
		self.stimer = QtCore.QTimer()
		#buttons
		QtCore.QObject.connect(self.ui.constant,QtCore.SIGNAL("clicked()"), self.constant)
		QtCore.QObject.connect(self.ui.single,QtCore.SIGNAL("clicked()"), self.single)
		
		# constant timer
		QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.constantUpdate)
		
		QtCore.QMetaObject.connectSlotsByName(self)
	
	def constant(self):
		"""
		Start the constant timer
		"""
		self.ctimer.start(1000)
		
	def constantUpdate(self):
		"""
		slot for constant timer timeout
		"""
		val = self.ui.constantProgress.value() + 10
		if val > 100:
			val = 0
		self.ui.constantProgress.setValue(val)
	
	def single(self):
		"""
		run singleShot timer after button push
		"""
		self.stimer.singleShot(1000, self.singleUpdate)
		
	def singleUpdate(self):
		"""
		Slot for singleShot timer timeout
		"""
		val = self.ui.singleProgress.value() + 10
		if val > 100:
			val = 0
		self.ui.singleProgress.setValue(val)

if __name__ == "__main__":
	app = QtGui.QApplication(sys.argv)
	myapp = timers()
	myapp.show()
	sys.exit(app.exec_())
Where the UI has two buttons and two progressbars:
timers1

Launching the constant timer will result in increasing after 1 second (1000 milliseconds) QProgressBar value. For the singleShot timer the value increase will happen only once. Constant timers use signal-slot system emitting timeout() signal. SingleShot timers are made using singleShot(time, receiver) method, where receiver is a method of our class, that will be run after specified amount of time.

You can download the example.

RkBlog

15 December 2008;

Comment article