0

在什么情况下 QQmlComponent::create(QQmlContext *) 返回 nullptr 失败?文档只说“如果创建失败则返回 nullptr”,没有进一步的细节。我的后端 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();

有谁知道为什么?谢谢!

4

1 回答 1

0

我认为它找不到您的 qml 文件。假设您的“ui-components/MessageDialog.qml”在 qrc 文件中,请尝试:

new QQmlComponent(&engine, QStringLiteral("qrc:/ui-components/MessageDialog.qml"));
于 2019-05-15T15:42:43.330 回答