簡體   English   中英

如何在QML中動態添加組件?

[英]How to dynamically add components in QML?

我正在嘗試按下按鈕時動態創建一個組件,然后將其添加到當前父級。 我不確定我在這里做錯了什么,

我有這個簡單的布局:

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文檔:

您需要在此處提供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});
                }
            }
        }
    }

我還創建了一個示例代碼 ,它也一樣,請看看

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM