【问题标题】:How to dynamically add components in QML?如何在 QML 中动态添加组件?
【发布时间】:2013-10-24 03:50:45
【问题描述】:

我试图在按下按钮时动态创建一个组件,然后将其添加到当前父级。我不确定我在这里做错了什么,

我有这个简单的布局:

import QtQuick 2.0
import Ubuntu.Components 0.1
import "components"
import "componentCreation.js" as MyScript

/*!
    \brief MainView with a Label and Button elements.
*/

MainView {
    // objectName for functional testing purposes (autopilot-qt5)
    objectName: "mainView"

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "com.ubuntu.developer..SpritePractice"

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true

    width: units.gu(100)
    height: units.gu(75)

    Page {
        title: i18n.tr("Simple")

        Column {
            spacing: units.gu(1)
            anchors {
                margins: units.gu(2)
                fill: parent
            }

            Button
            {
                text: i18n.tr("Hello World!!");
                onClicked:
                {
                    var component;
                    var sprite;
                    component = Qt.createComponent("Sprite.qml");
                    sprite = component.createObject(parent, {"x": 100, "y": 100});
                }
            }
        }
    }
}

这是我要添加的“精灵”:

import QtQuick 2.0

Rectangle { width: 80; height: 50; color: "red" }

如何将我正在创建的组件添加到当前父级?

如何解决:

我使用了下面的答案并使用了 Ubuntu 文档:

【问题讨论】:

    标签: qt qml ubuntu-touch


    【解决方案1】:

    您需要在此处提供 id,而不是 parent。

    sprite = component.createObject(parent, {"x": 100, "y": 100});
    

    尝试关注,

    Page {
            ...
    
            Column {
                id: container                
                ...
                Button
                {
                    text: i18n.tr("Hello World!!");
                    onClicked:
                    {
                        var component;
                        var sprite;
                        component = Qt.createComponent("Sprite.qml");
                        sprite = component.createObject(container, {"x": 100, "y": 100});
                    }
                }
            }
        }
    

    我还创建了一个sample code,也一样,请看一下

    【讨论】:

      猜你喜欢
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      相关资源
      最近更新 更多