Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QObject: Cannot create children for a parent that is in a different thread, but it works, why?



  • class MyThread : public QThread
    {
    public:
        virtual void run()
        {
            networkReply = networkAccessManager.get(QNetworkRequest(url));
        }
    private:
        QNetworkAccessManager networkAccessManager;
    }
    

    Runtime message:

    QObject: Cannot create children for a parent that is in a different thread.
    (Parent is QNetworkAccessManager(0x243bb066390), parent's thread is QThread(0x243b78951b0), current thread is StockIDUpdateTask(0x243bb066380)
    

    The message is caused by QNetworkAccessManager ::get(), but the function return a valid object pointer, and when connect networkReply.finished to a slot, it works.

    What to do with the runtime message?


  • Qt Champions 2019

    @jronald networkAccessManager is part of MyThread which itself is not the thread it manages. That means: run() is executed in the second thread but networkAccessManager is living in the thread which created MyThread instance. You should just create QNetworkAccessManager instance in run():

    class MyThread : public QThread
    {
    public:
        virtual void run()
        {
            networkAccessManager = new QNetworkAccessManager();
            networkReply = networkAccessManager->get(QNetworkRequest(url));
        }
    private:
        QNetworkAccessManager *networkAccessManager;
    }
    


  • This post is deleted!


  • @jsulm

    Yes, networkAccessManager .thread() is not MyThread, this is what confuses me, it works! Why?
    BTW, if networkAccessManager can be reused by multiple threads, it'll be appreciated.


  • Qt Champions 2019

    @jronald You should read this: https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
    It can work even if the instance is in another thread, but you should make sure it is in the same thread to avoid issues.


  • Moderators

    @jronald said in QObject: Cannot create children for a parent that is in a different thread, but it works, why?:

    it works! Why?

    This is called "Undefined Behaviour". It doesn't follow the rules, but it seems to work. However, the problem is: it might suddenly stop working in the future.

    So, don't use it, even though it works now.

    if networkAccessManager can be reused by multiple threads, it'll be appreciated.

    QNetworkAccessManager is meant for be used from 1 thread only. I recommend that you design your software to only use it from 1 thread: When your main thread finishes downloading, emit a signal to send the data to another thread.

    Anyway, may I ask why you want to use multiple threads?


Log in to reply