Important: Please read the Qt Code of Conduct -

Cannot create children for a parent that is in a different thread

  • I've creating an object (which inherits from QObject) in my main and passing this object to another thread i.e.


    QGuiApplication app(argc, argv);
    ClientListWrapper clients;
     if (!clients.initialize())
            return -1;
    args2thread->Pointer2clients = &clients;     // Passing this object to thread 
    std::thread Listening_thread(thread_function, args2thread);  // Creating a thread

    Now in my thread function I'm modifying client object i.e.


    //Receive data from client here
    args2thread->clients->addClient(data);  // Store the received data

    Why QT complains about it ? And how do i solve this

  • Lifetime Qt Champion

    Well you create ClientListWrapper clients; in the Main thread and simply
    assigning its adress to a variable won't move it.

    Have you considered using QThread and

  • I'm actually passing the address of clients variable to my thread. In that thread, I'm putting some data using that address. This approach works well in C++ but QT has some problem with this approach. It maybe because ClientListWrapper inherets from QObject (?)

  • Lifetime Qt Champion

    I would guess on that too even I have not mixed std::thread with QObjects before.
    The Qt way would be to emit the data from Listening_thread via a custom signal and
    have ClientListWrapper clients connect to that.

  • Lifetime Qt Champion

    You create a QObject derived class (and pass a parent) in the secondary thread which is not allowed. All objects of an object tree must live in the same thread. So you have two options - either move the whole object tree to the other thread or don't put the newly created QObject in the object tree from the main thread.

  • I've now used QThread instead of std::thread and used signal/slots to transfer data from my Listening_thread to main thread. problem solved.

    Thanks for the helpful replies.

Log in to reply