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?

- 77
- 3
- 20
1 Answers
Subclassing [see comment below]QThread
is a practice that is in general discouraged although often used.
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.

- 1
- 1

- 321,279
- 53
- 665
- 712
-
Subclassing `QThread` is not discouraged. The current [Qt documentation](http://doc.qt.io/qt-4.8/qthread.html#details) uses both approaches. The blog post you linked to is now outdated, as it refers to some older documentation that has now been re-written. See [this blog post](http://woboq.com/blog/qthread-you-were-not-doing-so-wrong.html) for more details. – ekhumoro Nov 09 '16 at 20:14
-
@ekhumoro Agreed, although I think subclassing still is dangerous, at least for people like me, who are not familiar with every nuance of the PyQt universe. – ImportanceOfBeingErnest Nov 09 '16 at 20:52
-
1Subclassing is never dangerous. The real "dangers" in multi-threading come from failing to ensure thread-safety. Very often in Qt, this usually involves trying to perform gui operations outside the main thread. There's no end of SO questions on that particular topic... – ekhumoro Nov 09 '16 at 22:02
-
SO...are there any good references with examples? I would like to see some practical applications to expand my knowhow – Daniel Nov 10 '16 at 00:57