Question

I've read there are two approaches for working with QThread. If I have a Worker class, which inherits QObject (as in http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/), then how should I create and manage local QEventLoop for working with signals/slots? I don't want to have memory leaks. How QNetworkAccessManager should be created in worker described in http://codethis.wordpress.com/2011/04/04/using-qthread-without-subclassing/?

Was it helpful?

Solution

If you don't subclass QThread, it has its own event loop (Fixed QThread documentation of Qt 5, also appliccable for Qt 4):

By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.

Managing the work done by the worker can be easily done using signals & slots:

(...) you are free to connect the Worker's slots to any signal, from any object, in any thread. It is safe to connect signals and slots across different threads, thanks to a mechanism called queued connections.

This means you usually don't need to care about any event loop on your own (unless you require special behaviour). Simply connect the thread's started signal to any slot of your worker object and make sure you set up some kind of deletion chain: Either the worker emits a signal which leads to the thread being stopped and deleted, or the other way round - both ways work, depending on your situation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top