[PyQt] thread in pyqt ... simple example needed

Arnold Krille arnold at arnoldarts.de
Sun Apr 5 20:08:32 BST 2009


On Sunday 05 April 2009 19:56:59 massimo di stefano wrote:
> Hi All,
> i'm doing my first experience using pyqt and tring to learn more about
> it
> unlucky i'm not able to solve some problems by myself :-(
> i tried to resume my problem in a sample script, that is :
> class Gui(QtGui.QWidget):
> 	def __init__(self, parent=None):
> 		QtGui.QGroupBox.__init__(self, parent)
> 		self.gcenter = QtGui.QPushButton("X", self)
> 		self.gcenter.setAutoRepeat(True)
> 		self.connect(self.gcenter, QtCore.SIGNAL("clicked()"),self.count)
> 		guiLayout = QtGui.QGridLayout()
> 		guiLayout.addWidget(self.gcenter,1,0)
> 		self.setLayout(guiLayout)
> 	def count(self):
> 		n = 0
> 		step = 1
> 		while True:
> 			n += step
> 			print n
> 			time.sleep(0.5)

This is a so called "busy-loop", a programming technic back from the days of 
DOS (the operating system). Don't use it. While the sleep-statement actually 
makes your app sleep for a certain time (so its not really a busy-loop), it 
still stops your app from execution during that time. Which means there are no 
repaints, button-clicks or anything else possible. You encounter that as "my 
app freezes".

The correct Qt-like way for such a loop is:
 - Either execute QCoreApplication.processEvents() inside the loop.
 - Or make your "heavy work" a slot that does just a little of the stuff in one 
step and then re-schedules itself either by QTimer.singleShot(...) or by 
adding a QTimer to your object and let it run continuously and connecting the 
timeout signal to your slot.


> as you can see the gui do not exit from the "while" statment
> and it freeze ...
> i know, i need to learn more about QTrhead usage...

No, if your level of experience is anywhere near the level I think it is, you 
will want to postpone any threads to a later day. There are actually very few 
problems that definitely need threads, Qt's slots combined with Qt's eventloop 
(automaticly used by the slots in my examples above) do a pretty good job for 
that.

Have fun,

Arnold
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part.
Url : http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20090405/526d47d0/attachment.bin


More information about the PyQt mailing list