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

How to replace model correctly?



  • Sorry for this newbie question, but I'm not sure how to do that correctly. I have a QTreeView and a custom model, derived from QAbstractItemModel. It can happen that the data, on which the model operates completely changes, that is, I pass a pointer to the data to the model and when the data changes, the pointer gets invalid. Thus, I try to remove the model beforehand and set it again after the data has changed.

    If I understood it correctly, I'm responsible for the deletion of the model, is that correct? Just doing a myTreeView->setModel(nullptr) would create a memory leak, I guess?

    And would it be feasible to do something like:

    delete ui_.salesView->model()
    // something that changes the data
    ui_.salesView->setModel(new SaleModel(getMarketplace(), ui_.salesView));
    

    Or is there a better way to handle this situation?


  • Lifetime Qt Champion

    The best way is this, oherwise the view will access to a dangling pointer during setModel() since it will disconnect the old model which is already deleted...

     auto model = ui.salesView->model();
     ui_.salesView->setModel(new SaleModel(getMarketplace(), ui_.salesView));
     delete model;
    

  • Moderators

    @Christian-Ehrlicher said in How to replace model correctly?:

    oherwise the view will access to a dangling pointer during setModel()

    Views connect to destroyed() signal of the model and detach from it automatically when it is destroyed so this is not true. At the call to setModel() there will already be no model attached to the view.

    So both ways are entirely correct.



  • Thanks a lot. So deleting the model is important and both ways are ok.

    @Christian-Ehrlicher :
    Wouldn't it be wise to call

    ui_.salesView->setModel(nullptr)
    

    directly after

    auto model = ui.salesView->model();
    

    to make sure that the model can't operate on invalid data. Or is that not a problem?


Log in to reply