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:

  1. class Worker : public QObject
  2. {
  3.     Q_OBJECT
  4.  
  5. public slots:
  6.     void doWork() {
  7.         /* ... */
  8.     }
  9. };
  10.  
  11. /* ... */
  12. QThread *thread = new QThread;
  13. Worker *worker = new Worker;
  14. //obj is a pointer to a QObject that will trigger the work to start. It could just be this
  15. connect(obj, SIGNAL(startWork()), worker, SLOT(doWork()));
  16. worker->moveToThread(thread);
  17. thread->start();
  18. //obj will need to emit startWork() to get the work going.

Alternatively, you could do:

  1. //based on the same Worker class as above:
  2.  
  3. /* ... */
  4. QThread *thread = new QThread;
  5. Worker *worker = new Worker;
  6. worker->moveToThread(thread);
  7. thread->start();
  8. QMetaObject::invokeMethod(worker, "doWork", Qt::QueuedConnection);

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].

Go back