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? http://qt-project.org/doc/qt-4.8/qthread.html#comments

    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 {
    Q_OBJECT

    public:
    MyThread();

    public slots:
    void testThreadSlot();

    signals:
    void testThreadSignal();
    };

    // Constructor
    MyThread::MyThread() {
    moveToThread(this);
    start();
    }

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

    Source: http://engineer-dan.tumblr.com/post/36274332373/subclassing-qthread





  • Sure it works, but still "you're doing it wrong":http://blog.qt.digia.com/blog/2010/06/17/youre-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.

    Thanks!



  • 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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.