I have a QList<QObject*>
C++ model containing custom objects and exposed to QML.
My custom object looks like this:
class CustomObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ getName NOTIFY nameChanged)
Q_PROPERTY(QQmlListProperty<CustomObject READ getChildren NOTIFY childrenChanged)
[...]
}
My model is exposed to QML like this:
qmlEngine->rootContext()->setContextProperty("internalModel", QVariant::fromValue(m_internalModel));
So far so good. I can use a view, display all my elements and recursively also display their children.
The problem is that QList has no way to notify QML that the model changed. As noted in the documentation about QObjectList-based model:
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 by calling QQmlContext::setContextProperty() again.
So everytime I add or remove an item, I call:
qmlEngine->rootContext()->setContextProperty("internalModel", QVariant::fromValue(m_internalModel));
And this is extremely slow.
If I understood correctly, I need to use QAbstractItemModel
instead.
So, is it possible to migrate from QList<QObject*>
to QAbstractItemModel
without changing the QML part? In particular, should I migrate all Q_PROPERTY
from CustomObject to roles or can "reuse them"?