PDA

View Full Version : pyqt: Start new thread and keep GUI reponsive whilst this new thread is still running



pazgs
6th December 2015, 14:18
Hi all,

There a problem I've been wrestling with when working in PyQt4 and it should be fairly simple... but I find it isn't.

I want to perform a calculation on another thread and have the GUI wait for the calculation to finish but remain responsive whilst waiting. By "responsive" I don't mean the user should be doing anything, I just don't want the GUI to freeze.

I have something like:

class worker(QObject):
def __init__(self, args):
super(worker, self).__init__()

print QThread.currentThreadId()

self.args = args

start = pyqtSignal()

def __del__(self):
pass

@pyqtSlot()
def run(self):

print QThread.currentThreadId()
'''do a long calculation using self.args'''




myworker = worker(args)

mythread = QtCore.QThread()
print mythread.currentThreadId()

mypcaworker.moveToThread(mythread)
mythread.started.connect(mypcaworker.run)
print mythread.currentThreadId()

mythread.start()
print mythread.currentThreadId()

// keep the GUI responsive until the long calc on another thread has finished
while mythread.isRunning():
QtGui.QApplication.processEvents()




You will notice that I print the thread Id in several places. The output tells me that only the run method is running on a different thread and so the while loop is an inifinite loop because mythread is running on the GUI thread, not the worker thread that run is running on. How can I keep running QtGui.QApplication.processEvents() until run has finished executing?

Any help with this would be greatly appreciated. Many thanks in advance

anda_skoa
6th December 2015, 17:12
currentThreadId() is a static method, it prints the ID of the thread executing it.
So whenever you call it from the main thread, it evaluates to the main thread's ID.

Cheers,
_