How to use QThread correctly in pyqt with moveToThread()?

The default run() implementation in QThread runs an event loop for you, the equivalent of:

class GenericThread(QThread):
    def run(self, *args):
        self.exec_()

The important thing about an event loop is that it allows objects owned by the thread to receive events on their slots, which will be executed in that thread. Those objects are just QObjects, not QThreads.

Important note: the QThread object is not owned by its own thread [docs]:

It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread’s queued slots and invoked methods will execute in the old thread [e.g. the main thread].

So you should be able to do this:

class GenericWorker(QObject):
    def __init__(self, function, *args, **kwargs):
        super(GenericWorker, self).__init__()

        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.start.connect(self.run)

    start = pyqtSignal(str)

    @pyqtSlot()
    def run(self, some_string_arg):
        self.function(*self.args, **self.kwargs)

my_thread = QThread()
my_thread.start()

# This causes my_worker.run() to eventually execute in my_thread:
my_worker = GenericWorker(...)
my_worker.moveToThread(my_thread)
my_worker.start.emit("hello")

Also, think carefully about what happens with the result of self.function, which is currently discarded. You could declare another signal on GenericWorker, which receives the result, and have the run() method emit that signal when it’s done, passing the result to it.

Once you get the hang of it and realize you don’t and shouldn’t subclass QThread, life becomes a lot more straightforward and easier. Simply put, never do work in QThread. You should almost never need to override run. For most use cases, setting up proper associations with a QObject to a QThread and using QT’s signals/slots creates an extremely powerful way to do multithreaded programming. Just be careful not to let the QObjects you’ve pushed to your worker threads hang around…

http://ilearnstuff.blogspot.co.uk/2012/09/qthread-best-practices-when-qthread.html

Leave a Comment