QQmlApplicationEngine没有完全卸载qml组件。

问题描述 投票:0回答:1

我目前使用QQmlApplicationEngine加载我的main.qml,工作正常,然后我想切换到main2.qml(不需要在我的QQmlApplicationEngine上调用quit(),因为那样会触发QCoreApplication::exit(),从而退出我的应用程序)。所以我只是删除了我的引擎,做了一个新的引擎,然后重新设置上下文属性(和main.qml的上下文属性略有不同),就能正常加载。然后我切换回main.qml(再次加载main.qml),我开始收到如下警告

qrc:/qml/...: Cannot read property of null

该属性在main.qml的上下文中是空的,所以这是正确的,但在main2.qml的上下文中不是空的。但我的问题是,为什么我第一次加载main.qml时没有收到警告?我似乎只有在加载main2.qml之后再加载main.qml时才会收到警告。

感谢您的帮助。

EDIT: 下面是一个简单的示例代码

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")));
    }
}
qt qml qqmlengine
1个回答
1
投票

我想推荐你使用一个QML Loader组件来改变当前可查看的视图。在这个页面上,你可以找到一些如何使用Loader(s)的例子。https:/doc.qt.ioqt-5qml-qtquick-loader.html。.

在这种情况下,你必须同时为 "object1 "和 "object2 "提供上下文属性。

© www.soinside.com 2019 - 2024. All rights reserved.