我目前正在使用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时才会收到警告。
非常感谢您的帮助。
编辑:下面是一个简单的示例代码
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")));
}
}发布于 2020-05-24 02:05:52
我建议您使用QML Loader组件来更改当前的可视视图。在此页面上,您可以找到几个如何使用Loader(s) https://doc.qt.io/qt-5/qml-qtquick-loader.html的示例。
在这种情况下,您必须提供"object1“和"object2”的上下文属性。
https://stackoverflow.com/questions/61964560
复制相似问题