[PyQt] update qt labels from another thread

Roberto Alsina ralsina at kde.org
Wed Apr 11 13:38:12 BST 2007

On Wed 11 Apr 2007 09:13:33 Pradnyesh Sawant wrote:
> Hello,
> I have a Qt4 form, which contains some labels, and 2 buttons "start"
> and "stop". The start button, when clicked, creates an instance of a
> python class which does some communication over sockets in another
> independent thread of its own. The stop button kills the instance
> created above, and kills the thread.
> What i want to do is to update the text of my form labels with the
> data that i receive over the socket communication. For this reason, i
> sent the "form" object to the backend class object, and tried updating
> the form labels from within the thread doing the socket communication.
> However, i get an error saying that Qt objects cannot be modified from
> other threads :(
> How do i achieve updates of form labels? In a previous mail on this
> list itself, i read something about signals/slots/callbacks. I don't
> see how signals/slots will be helpful here (however, plz note that i
> am relatively new to PyQt4 and this might be incomplete knowledge on
> my part). As far as callbacks are concerned, i don't know what they
> mean. Any pointers/tutorials for me would be greatly helpful...

If the answer is "use signals and slots"...

Keep in mind that the code below is written without any testing, and I am not 
even sure if signals/slots actually work cross-threads in Qt4 ;-)

Suppose the form has a "setLabelText" function like this:

def setLabelText(self,newtext):

And the "object in another thread" wants to update it. You need to make that 
object inherit QtCore.QObject (or use a QSignal object... those still exist 
in Qt4, right?)

Then the object can do this:

emit (QtCore.SIGNAL("newData"),"data")

If you previously connected that object's newData signal to the form's 
setLabelText slot... you are golden, regardless of on what thread the signal 
is emitted, I suppose.
 ("\''/").__..-''"`-. .         Roberto Alsina
 `9_ 9  )   `-. (    ).`-._.`)  ralsina at kde.org
 (_Y_.)' ._   ) `._`.  " -.-'   KDE Developer (MFCH)
  _..`-'_..-_/ /-'_.'
(l)-'' ((i).' ((!.'   Buenos Aires - Argentina

Debugging is twice as hard as writing the code in the first place. 
Therefore, if you write the code as cleverly as possible, you are, 
by definition, not smart enough to debug it. --Brian W. Kernighan 

More information about the PyQt mailing list