[PyQt] processevents needed for qthreads?

Peter Bienstman Peter.Bienstman at ugent.be
Fri Aug 12 10:12:00 BST 2011


Hi,

I have a threaded program which works fine under Linux, but crashes sometimes 
under Windows. My suspicion is that this is because I use 
QtCore.QCoreApplication.processEvents, for which I read everywhere that this 
is to be avoided and is a crutch for poor design.

Also, many tutorial examples don't seem to require processEvents, but in my 
case, slots in the GUI main thread don't soom to get called unless I use  
processEvents.

I'm obviously missing something about threads and Qt here, but can somebody 
have a look at my code and see what is going wrong?

Thanks!

Peter

import sys
import time

from PyQt4 import QtCore, QtGui

class Worker(QtCore.QObject):

    update_progress_signal = QtCore.pyqtSignal(int)
    finished_signal = QtCore.pyqtSignal()
    
    def __init__(self):
        QtCore.QObject.__init__(self)

    def do_work(self):
        for i in range(6):
            self.update_progress_signal.emit(i)
            print 'signal emitted', i
            time.sleep(1) # Stand-in for doing some heavy work.
        self.finished_signal.emit()
         
class Server(QtCore.QObject):

    def __init__(self, widget):
        QtCore.QObject.__init__(self)
        self.progress_bar = QtGui.QProgressDialog(widget)
        self.progress_bar.setRange(0, 5)
        worker = Worker()
        thread = QtCore.QThread()        
        worker.moveToThread(thread)
        thread.started.connect(worker.do_work)
        worker.update_progress_signal.connect(self.show_progress)
        worker.finished_signal.connect(thread.quit)
        thread.start()

        working_version = True
        if working_version:
            while thread.isRunning():
                QtCore.QCoreApplication.processEvents(\
                    QtCore.QEventLoop.ExcludeUserInputEvents)
            thread.wait(100)
        else:
            thread.wait()

    def show_progress(self, i):
        print 'slot called', i
        self.progress_bar.setValue(i)
     

app = QtGui.QApplication(sys.argv)

widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('Thread test')
widget.show()


More information about the PyQt mailing list