为什么 QQmlComponent::create() return nullptr?
Why does QQmlComponent::create() return nullptr?
在什么情况下QQmlComponent::create(QQmlContext *)会返回nullptr失败?文档只说“Returns nullptr if creation failed”,没有进一步的细节。我的后端 C++ 代码尝试从以下 qml 实例化 MessageDialog:
import QtQuick 2.0
import QtQuick.Dialogs 1.1
MessageDialog {
id: messageDialog
title: "My message"
text: "Fill in this message from C++"
onAccepted: {
console.log("Knew you'd see it my way!")
// Hide the dialog
visible = false
}
Component.onCompleted: visible = true
}
这是我的后端构造函数的片段:
QQmlApplicationEngine engine;
// Note that component resource is local file URL,
// not network - no need to wait before calling create()?
QQmlComponent *component =
new QQmlComponent(&engine,
QStringLiteral("ui-components/MessageDialog.qml"));
// Following call returns nullptr
QObject *childItem = component->create();
有人知道为什么吗?谢谢!
我认为它没有找到您的 qml 文件。假设您的 "ui-components/MessageDialog.qml" 在 qrc 文件中,尝试:
new QQmlComponent(&engine, QStringLiteral("qrc:/ui-components/MessageDialog.qml"));
在什么情况下QQmlComponent::create(QQmlContext *)会返回nullptr失败?文档只说“Returns nullptr if creation failed”,没有进一步的细节。我的后端 C++ 代码尝试从以下 qml 实例化 MessageDialog:
import QtQuick 2.0
import QtQuick.Dialogs 1.1
MessageDialog {
id: messageDialog
title: "My message"
text: "Fill in this message from C++"
onAccepted: {
console.log("Knew you'd see it my way!")
// Hide the dialog
visible = false
}
Component.onCompleted: visible = true
}
这是我的后端构造函数的片段:
QQmlApplicationEngine engine;
// Note that component resource is local file URL,
// not network - no need to wait before calling create()?
QQmlComponent *component =
new QQmlComponent(&engine,
QStringLiteral("ui-components/MessageDialog.qml"));
// Following call returns nullptr
QObject *childItem = component->create();
有人知道为什么吗?谢谢!
我认为它没有找到您的 qml 文件。假设您的 "ui-components/MessageDialog.qml" 在 qrc 文件中,尝试:
new QQmlComponent(&engine, QStringLiteral("qrc:/ui-components/MessageDialog.qml"));