How to dynamically add components in QML?

蹲街弑〆低调 提交于 2019-12-14 00:16:19

问题


I am trying to create a component on the fly when a button is pressed, then add it to the current parent. I'm not sure what I am doing wrong here,

I have this simple layout:

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

Here is my "sprite" that I am trying to add:

import QtQuick 2.0

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

How can I add the component I am creating to the current parent?

How to resolve:

I used the answer below and I used the Ubuntu documentation:

  • http://developer.ubuntu.com/api/qml/sdk-1.0/QtQml.qtqml-javascript-dynamicobjectcreation/#creating-objects-dynamically

回答1:


You need to provide id here, instead of parent.

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

Try following,

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

I also created a sample code, which does same, Please have a look



来源:https://stackoverflow.com/questions/19533565/how-to-dynamically-add-components-in-qml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!