user1899020
user1899020

Reputation: 13575

Is it fine to change model data internally before displaying views?

Is it fine to change model data internally before displaying views? For example

struct MainWindow : QMainWindow
{
    MainWindow()
    {
       mTreeView->setModel(mModel);
       mModel->appendChild(...); // No beginInsertRows() and similars are called
    }
};

Although the model is set to the view before changing the model data, the view is not displayed since it is done in the constructor of main window. If the view is updated when it is displayed, I think the code should be okay.

Upvotes: 1

Views: 71

Answers (2)

vahancho
vahancho

Reputation: 21220

It is fine to do so - your program will not crash, at least. However when you add new items to the model in the way you show in your example, your view will not display the update, especially if you do not use beginInsertRows(). If you want the view properly show the actual data, try to set model after you insert items in it. Otherwise you will need to call beginInsertRows() and endInsertRows() in your model class.

Upvotes: 0

mhcuervo
mhcuervo

Reputation: 2660

When the model is already connected to one or more views I totally recommend calling the corresponding begin... and end... methods before and after the model modification. Those functions emit the signals which connected views (or proxies) must handle before and after the data is modified. Otherwise, the views may end up in an invalid state. When no views (or proxies) are connected it is safe to do so.

Upvotes: 1

Related Questions