qt - 如何在QML中动态添加组件?

标签 qt qml ubuntu-touch

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

我有这个简单的布局:

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});
                }
            }
        }
    }
}

这是我要添加的“sprite”:
import QtQuick 2.0

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

如何将要创建的组件添加到当前父组件?

解决方法:

我使用以下答案,并使用Ubuntu文档:
  • http://developer.ubuntu.com/api/qml/sdk-1.0/QtQml.qtqml-javascript-dynamicobjectcreation/#creating-objects-dynamically
  • 最佳答案

    您需要在此处提供ID,而不是父级。

    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,它也一样,请看看

    关于qt - 如何在QML中动态添加组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19533565/

    相关文章:

    c++ - 从Qml中的QSqlTableModel中删除一行时的 View 不一致

    c++ - QTcpSocket stateChanged 是否适用于心跳检查?

    qt - Qml样条图中的异常

    c++ - 从 Q_INVOKABLE 函数或插槽中更改 QQuickImage 源

    qt - QML如何绘制与grabToImage()不同的图像

    c++ - 如何从图像文件创建圆形图标?

    qt - 替换 console.debug() 的日志记录后端 console.warn()

    java - 编译 Ubuntu Touch 无规则使目标为 "APPS/../src/R.stamp"

    qml - 根据属性值有条件地包含组件