How to dynamically add components in QML?

John picture John · Oct 23, 2013 · Viewed 26.2k times · Source

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:

Answer

Kunal picture Kunal · Oct 23, 2013

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