Is this correct, to have a thread calling slot in main process?



  • I was getting the following error in Qt5 because my MainWindow dropped a thread that was trying to update a treeview in the main thread.

    QObject: Cannot create children for a parent that is in a different thread.
    

    So in my thread class (derived from QObject) I have this function which takes the MainWindow object to which the slot will be called.

    void MyTest::set_model(MainWindow &mw)
    {
        connect(this, SIGNAL(update_tree), mw, SLOT(update_treeview),              
            Qt::QueuedConnection);
    }
    
    void MyTest::update_tree()
    {
        std::cout << "update_tree ........" << std::endl;
    }   
    

    And in my MainWindow, here is how I pass the MainWindow object to the thread so that it can emit a signal and call a slot in the main thread (TBD: emit signal).

    void MainWindow::update_treeview()
    {
        std::cout << "calling update_treeview() ..." << std::endl;
    }
    
    MyTest *test = new MyTest;
    test->set_model(this, tree_model, tree_view);
    
    std::thread t(test);
    t.join();
    

    It doesn't yet compile, but am I going about this correctly? My goal is to have the thread pass TreeModel data to the main process so the TreeView can be updated.


  • Lifetime Qt Champion

    Hi,

    If you want a model with thread support, you should check the implementation of QFilesystemModel.



  • I have a custom model and am not using QFilesystemModel? Should the above work?


  • Qt Champions 2018

    The short answer is that ther's a 99.9999% chance what you are doing is wrong.
    The model can't be read nor written from a non-gui thread if that model is connected to a view.
    The view calls methods from the model directly so any operation on the model from a different thread is a race condition.
    The correct way to do it is to emit a signal with the new data from the secondary thread and have the gui thread do the actual update


  • Lifetime Qt Champion

    I didn't wrote you had to use QFileSystemModel but that you could get inspiration from it as its implementation uses thread and does it as @VRonin correctly describes it.



  • I don't think @VRonin got what I was saying in my OP, but what I explained in my OP sounds exactly like what VRonin explained, so I think I'm on the right track. Thanks both.


Log in to reply
 

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