Subclassing no longer recommended way of using QThread
The documentation above still only gives a sample of using QThread by subclassing it. That is no longer needed, and actually no longer the recommended standard way of using QThread. QThread must be thought of as a class to manage a thread, but not as the actual code or object that runs in that thread. To use QThread to manage a thread, subclassing is hardly ever needed. Instead, create a worker object that derives from QObject, and implement a slot on that worker to perform the work you need doing.
Consider the following pattern as your default way to use QThread:
- {
- Q_OBJECT
- public slots:
- void doWork() {
- /* ... */
- }
- };
- /* ... */
- Worker *worker = new Worker;
- //obj is a pointer to a QObject that will trigger the work to start. It could just be this
- connect(obj, SIGNAL(startWork()), worker, SLOT(doWork()));
- worker->moveToThread(thread);
- thread->start();
- //obj will need to emit startWork() to get the work going.
Alternatively, you could do:
- //based on the same Worker class as above:
- /* ... */
- Worker *worker = new Worker;
- worker->moveToThread(thread);
- thread->start();
Many more hints and details, including the pitfalls of using QThread in combination with signals and slots, can be found this must read wiki article [developer.qt.nokia.com].