QTimer - making timers 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.ctimer = QtCore.QTimer()
		self.stimer = QtCore.QTimer()
		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)
	def constant(self):
		Start the constant timer
	def constantUpdate(self):
		slot for constant timer timeout
		val = self.ui.constantProgress.value() + 10
		if val > 100:
			val = 0
	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

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

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.


PyQt and GUI, 15 December 2008, Piotr MaliƄski

Comment article
RkBlog main page Search RSS Contact