0

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")));
    }
}
blessedone
  • 160
  • 1
  • 8
  • please provide a [mre] – eyllanesc May 22 '20 at 22:20
  • Apart from the fact that reloading QML root file is a strange idea and recreating QML engine (that's an even stranger idea) why not reuse `QQmlApplicationEngine::load()` with the new file? – folibis May 23 '20 at 08:48
  • @folibis what do you mean reuse QQmlApplicationEngine::load()? Just call m_engine->load() with out recreating QML engine? – blessedone May 25 '20 at 16:24

1 Answers1

1

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".

Skident
  • 326
  • 1
  • 5