【问题标题】:New qml object added to scene in c++在 C++ 中将新的 qml 对象添加到场景中
【发布时间】:2015-06-16 17:28:25
【问题描述】:

我在将新 QML 对象添加到现有场景时遇到问题。

我的main.qml 来源:

ApplicationWindow    
{
id:background
visible: true
width: 640
height: 480
}

MyItem.qml来源:

Rectangle 
{
width: 100
height: 62
color: "red"
anchors.centerIn: parent
}

最后,这是我的main.cpp 来源:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QQmlComponent *component = new QQmlComponent(&engine);
    component->loadUrl(QUrl("qrc:/MyItem.qml"));

    qDebug() << "component.status(): "<< component->status();

    QObject *dynamicObject  = component->create();
    if (dynamicObject == NULL) {
        qDebug()<<"error: "<<component->errorString();;
    }

    return app.exec();
}

main.qml 正确显示,但 MyItem.qml 未出现在 main.qml 中。 Component.status() 返回状态 ReadydynamicObject 上没有错误。我做错了什么?

【问题讨论】:

    标签: qt qml qtquick2 qqmlcomponent qqmlapplicationengine


    【解决方案1】:

    您需要为项目指定一个父项,否则它不是视觉层次结构的一部分并且不会被渲染。

    【讨论】:

      【解决方案2】:

      我认为您应该使用QQuickView 而不是QQmlEnginemain.cpp 将是:

      int main(int argc, char *argv[]) {
          QGuiApplication app(argc, argv);
      
          QQuickView view;
          view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
          view.show();
      
          QQmlComponent component(view.engine(), QUrl("qrc:/MyItem.qml"));
      
          QQuickItem *item = qobject_cast<QQuickItem*>(component.create());
          item->setParentItem(view.rootObject());
          QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);
      
          return app.exec();
      }
      

      您需要将main.qml 类型从ApplicationWindow 更改为Item

      Item
      {
          id:background
          visible: true
          width: 640
          height: 480
      }
      

      这样更容易,您可以创建一个扩展QQuickView 的类,并管理新项目的创建。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2015-03-12
        相关资源
        最近更新 更多