Cannot add model to QML
-
Your MainWindow is creating another QML engine which does not have "DataModel" set.
-
@milan said in Cannot add model to QML:
QQmlApplicationEngine* engine = new QQmlApplicationEngine();
remove the engine since you're not using it anywhere. Or remove MainWindow if you are not using that. I don't know which is true in your case.
Extract the engine from your
ui->quickWidget
and add the DataModel there. If you are using QQuickWidget, you can use https://doc.qt.io/qt-5/qquickwidget.html#engine. -
@milan said in Cannot add model to QML:
qDebug() << "Setting value:" << num;
Do you see this message printed?
-
@milan said in Cannot add model to QML:
@sierdzio . I see that DataModel object gets destructed after it is constructed.
So make sure it lives long :-)
-
@milan said in Cannot add model to QML:
@sierdzio. Yes I did that. Is qmlregistertype better way that setContextProperty I am using now? The C++ model should update the qml
No it is not better, it server a different purpose. It makes the type recognizable (and creatable) in QML. Since you want to use a global data model (I think), then setting the context property is a better way for your use case. Just make sure DataModel object is not destroyed while your UI is alive. You can do it, for example, by declaring it as a member variable of MainWindow class, or by creating an object on heap and assigning MainWindow as parent.