Important: Please read the Qt Code of Conduct -

Subclassing QThread - Changing the community note

  • I've found a work-around to the common notion that it's not ideal to subclass QThread (at least for version 4.8). So far in my testing, I haven't come across any issues.

    I believe this solution is preferable because it promotes encapsulation, removes the worker object, as well as removes connect() calls between the thread and the worker.

    If this is method is agreed to be ideal, how do I proceed to changing the community note at the bottom of the QThread documentation page which states that subclassing QThread is not recommended?

    Proposed solution:

    By calling moveToThread(this) within the contructor of a class derived from QThread, the class has fully functional cross-threading signals and slots.

    @// Subclassing QThread
    class MyThread : public QThread {


    public slots:
    void testThreadSlot();

    void testThreadSignal();

    // Constructor
    MyThread::MyThread() {

    // Slot...@

    In the code below, the slots will execute within the thread they are defined.

    @connect(this, SIGNAL(testMainSignal()), &myThread, SLOT(testThreadSlot()));
    connect(&myThread, SIGNAL(testThreadSignal()), this, SLOT(testMainSlot()));@

    The only caveat I know of is if you override QThread::run(), you must call exec() within run(), or else the signals and slots won't work.


  • Sure it works, but still "you're doing it wrong": .

  • Ah, I saw a similar link to this article but it pointed to nokia, thus me not seeing it.

    In my case I found the moveToThread(this) solution to be the most elegant.

    However I guess I'll leave it at that. Even though I think it would be helpful for this solution to be in the notes, I believe users can infer it on their own anyways.


  • The new documentation for 5.0 will be updated to promote the best practise of not subclassing QThread. Hopefully this will end all the questions related to subclassing QThread and the problems that arise from this.

Log in to reply