[PyQt] QThread Behaviour

Mladen Milankovic mmlado at gmail.com
Tue Jun 17 15:47:42 BST 2008


On Tuesday 17 June 2008 16:23:01 David Klasinc wrote:
> Greetings,
>
>   After QThread.run() was called, shouldn't calling thread continue with
> its execution and not wait for the thread to finish? Shortened example
> follows
>
>
> class myThread (QtCore.QThread):
>   def run (self):
>    print "T 1"
>    sleep 1
>    print "T 2"
>    sleep 1
>    print "T 3"
>
> thread = myThread()
> print "Foo"
> thread.run()
> sleep 1
> print "Bar"
>
> And The result is
>
> Foo
> T 1
> T 2
> T 3
> Bar
>
> Shouldn't it be:
>
> Foo
> T 1
> Bar
> T 2
> T 3
>
> Anyone can shed some light on this?
>
> rgrds,
> David

Hi.

You need to call QThreads start function to start the thread in a separate 
thread. The start function will eventually call the run function which you 
can oweride if needed. 
As I understood the start function does a little magic, creates a new thread 
and in that thread runs the run function.

My script:

from PyQt4.QtCore import *
import time

class myThread (QThread):
  def run (self):
    print "T 1"
    time.sleep (1)
    print "T 2"
    time.sleep (1)
    print "T 3"

thread = myThread()
print "Foo"
thread.start()
time.sleep(1)
print "Bar"

Output:
Foo
T 1
T 2
Bar

The print "T 3" line won't ever execute because the script finishes before. If 
you want to run the script you should create a "loop" through 
QCoreApplication and it's function exec_ and connect the QThread signal to a 
slot(function) which will exit the script.

regards
mmlado


More information about the PyQt mailing list