Search code examples
gridviewqmlqabstractlistmodel

Change QML GridView model at run time


I have a QAbstractListModel based class defined in QT and in QML I have set this model to a GridView. It works perfect. If I change data in the model I call the reset function and GridView shows the updated data. But at time I change the complete model data (i.e Not just the data changes but also its count changes). In this case when I reset the data the GridView does not show the updated model. I have also tried to create a new object of my model and changed the GridView model but still no effect.

Here are the basic code snippet.

// DataEngine.h
class DataEngine : public QAbstractListModel
{
    Q_OBJECT
public:
    .....
public: // Overrides
    int rowCount(const QModelIndex &parent) const;
    QVariant data(const QModelIndex &index, int role) const;
}
// main.c
DataEngine *data = new DataEngine();
view.rootContext()->setContextProperty("DataModel", data)

// QML File
GridView {
.....
id: view
model: DataModel
.....
}

// After completely changing data (i.e earlier it has 256 rows, now it has say 0 row)
// I tried
view.rootContext()->setContextProperty("NewDataModel", data)
// QML Code
view.model = NewDataModel     // No effect.

It seems to me the data is changing but GridView is not updating with the new data.

Any help is appreciated.

Best Regards, Farrukh Arshad


Solution

  • I suspect you're failing to notify the underlying base model that your data has changed. See this section of the QAbstractItemModel for details on what you need to do in your child class. In particular, the following sentence says quite a bit:

    When implementing these functions, it is important to notify any connected views about changes to the model's dimensions both before and after they occur:

    If you are removing reducing the data then you have to provide implementation of removeRows and if you are increasing data then you have to provide the implementation of insertRows. In my case since I had data from my own sources, I just deleted that data and was returning rowIndex as 0 that didn't worked. I have just added an empty implementation of removeRows with beginRemoveRows & endRemoveRows inside return true, and emitted this signal. With this signal my view knows the data count is changed so it has called rowCount function where I have returned 0.