Search code examples
pyqt4qthread

Can you create a separate QThread class and only call a specific function from it?


I have tried to read as much as I can about PyQt4's QThread and the idea of the worker thread. My question is, instead of building a QThread class to run everything in it from the def run(self): by the blahblah.start() command is there a way to create that individual thread class that has,say, 4 functions and you only call function 2 and then close that thread right after?


Solution

  • Subclassing QThread is a practice that is in general discouraged although often used. [see comment below]

    In my opinion, this is a good example of how to use a thread in pyqt. You would create a Worker and a Thread, where the Worker is some general class of type QObject and the Thread is a QThread which you do not subclass. You'd then move the Worker to the Threat and start it.

        self.worker = WorkerObject()
        self.worker_thread = QtCore.QThread()
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()
    

    Inside the Worker you can basically do whatever you want, it can have arbitrary many methods and so on.
    The one big thing to keep in mind is that the Worker needs to be separate from the main loop. So the methods should not return anything that is used in the main loop (better not return anything at all) and the Worker's results should be collected using signals and slots.

    self.button_start.clicked.connect(self.worker.startWork)
    self.button_do_something_else.clicked.connect(self.worker.function2)
    self.worker.signalStatus.connect(self.updateStatus)
    

    Also make sure not to use any PyQt/GUI objects inside the worker, as this would also build a bridge between Worker and main loop through PyQt itself.