CodexBloom - Programming Q&A Platform

Qt QML ListView not updating when model changes - unexpected behavior

👀 Views: 100 💬 Answers: 1 📅 Created: 2025-06-13
Qt QML ListView C++ QAbstractListModel

Hey everyone, I'm running into an issue that's driving me crazy..... I'm working with Qt 5.15 and I have a `ListView` in QML that is bound to a `ListModel`. However, when I update the model data using `QAbstractListModel` in C++, the UI does not refresh as expected. The `ListView` displays the old data and doesn't reflect the latest changes. I’ve ensured that my model emits the appropriate signals like `dataChanged` when the data changes, yet the view does not update. Here's a simplified version of my C++ model implementation: ```cpp class MyModel : public QAbstractListModel { Q_OBJECT public: enum Roles { NameRole = Qt::UserRole + 1, AgeRole }; MyModel(QObject *parent = nullptr) : QAbstractListModel(parent) {} QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { if (!index.isValid() || index.row() >= items.size()) return QVariant(); if (role == NameRole) return items[index.row()].name; if (role == AgeRole) return items[index.row()].age; return QVariant(); } void updateItem(int row, const QString &newName, int newAge) { if (row < 0 || row >= items.size()) return; items[row].name = newName; items[row].age = newAge; emit dataChanged(index(row), index(row)); // This should notify the view } private: QVector<Item> items; // Item is a struct containing name and age }; ``` In my QML file, I have the following setup: ```qml ListView { model: myModel delegate: Text { text: model.name } } ``` I call `updateItem` from a button click handler in C++ to modify the data. For some reason, the changes are not appearing in the `ListView`. I've also tried adding `beginResetModel()` and `endResetModel()` around the data updates, but I would lose the current selection in the list, which I want to avoid. When I debug, I see that `dataChanged` is being emitted, but the UI still does not reflect the changes. Is there something I'm missing regarding the connection between the model and the view, or do I need to use a different approach for updating the data? I'm working on a API that needs to handle this. My development environment is Ubuntu. Thanks for any help you can provide!