I'm currently loading my main.qml using QQmlApplicationEngine and works fine, and then I want to switch to main2.qml (without calling quit() on my QQmlApplicationEngine since that triggers QCoreApplication::exit() which will exit my application). So I just delete my engine, make a new one and set the context properties again (not the same context properties for main.qml slightly different), and it loads fine. Then I switch back to main.qml (load main.qml again) and I start getting warnings like
qrc:/qml/...: Cannot read property of null
That particular property is null in the context of main.qml so this is correct, but it is not null in the context of main2.qml. But my question is why don't I get the warning when I load main.qml the first time? I only seem to get the warning if I load main.qml after I have loaded main2.qml.
Your help is appreciated.
EDIT: Here is a simple example code
QSharedPointer<QQmlApplicationEngine> m_engine;
QQmlContext* m_ctxt;
void loadEngine(int window){
m_engine->clearComponentCache();
m_engine.reset(new QQmlApplicationEngine, &QObject::deleteLater);
m_ctxt = m_engine->rootContext();
m_ctxt->setParent(m_engine.get());
QVector<QQmlContext::PropertyPair> qmlProperties;
qmlProperties.push_back(QQmlContext::PropertyPair{"object", QVariant::fromValue(object)});
if(window == 1){
qmlProperties.push_back(QQmlContext::PropertyPair{"object1", QVariant::fromValue(object1)});
// add more context properties
m_ctxt->setContextProperties(qmlProperties);
m_engine->load(QUrl(QLatin1String("qrc:/qml/main.qml")));
}
else{
qmlProperties.push_back(QQmlContext::PropertyPair{"object2", QVariant::fromValue(object2)});
// add more context properties
m_ctxt->setContextProperties(qmlProperties);
m_engine->load(QUrl(QLatin1String("qrc:/qml/main2.qml")));
}
}
I'd like to recommend you use a QML Loader component to change current viewable view. On this page you can find a few examples how to use Loader(s) https://doc.qt.io/qt-5/qml-qtquick-loader.html.
In this case you have to provide both context properties for "object1" and "object2".