Qt offers the possibility to combine C++ models with QML and suggests three approaches in the docs:
QStringList
QObjectList
QAbstractItemModel
The two former are extremely simple to use, e.g. QObjectList
:
// in C++
QList<QObject*> dataList;
dataList.append(new DataObject("Item 1", "red"));
// in QML
ListView {
model: dataList
delegate: Text { text: name }
}
but they both come with a strong caveat:
Note: There is no way for the view to know that the contents of a QList has changed. If the QList changes, it is necessary to reset the model [...]
QAbstractItemModel
is difficult to use with objects because the objects properties are not directly exposed and therefore keeping them in sync takes quite a bit of effort.
However, it is possible to wrap a QList
in a QAbstractItemModel
and obtain a super simple model. See here: Implementation 1, Implementation 2
Is there a reason why Qt does not implement this natively? Performance? Memory management issues? It seems such an obviously good idea and with ObjectModel
they already implement something similar.