PDA

View Full Version : Waiting for QThread without interupting main thread



ecce
14th May 2016, 10:45
How do you wait for a qthread to finish without blocking the main loop (thereby blocking the responsiveness of the main window)? I'm using PyQt5.


# When scan button is pressed
def scan(self, e):
for dev in self.deviceList:
thread = TestThread(self, dev)
thread.debugOutput.connect(self.updateTextEdit)
thread.start()
print("Thread finished")

The thread(s) started in this piece of code do GUI updates to inform the user of what's going on. I do not want to block that. I want the "thread finished" to be printed out once the thread actually is finished.

anda_skoa
14th May 2016, 11:11
QThread has a finished() signal.

Cheers,
_

ecce
14th May 2016, 20:54
Like this?



# When scan button is pressed
def scan(self, e):
for dev in self.deviceList:
thread = TestThread(self, dev)
thread.debugOutput.connect(self.updateTextEdit)
thread.start()
thread.finished.connect(self.isFinished)

def isFinished(self):
print("Thread finished")


I thought I might post it here, it took me a while to figure it out (newbie section, right?)

anda_skoa
15th May 2016, 08:30
Like this?

Not quite.

You need to connect before you call start, otherwise the thread could have started and finished before the caller thread had a chance to establish the connection.

The most important principle of multithread programming is to never make assumptions of when something gets executed, unless such an assumption is enforced by means like synchronization or, like in this case, doing things before there is any concurrent execution.

Cheers,
_