首页 > 解决方案 > 如何设置动态创建的对象的一个​​或多个属性?

问题描述

我的问题很简单。如果我动态创建了一个 qml 组件,我该如何设置它的属性?
在这个我的示例中,我想在单击按钮元素时更改颜色

Window {
    id:win
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Component.onCompleted: {

      var comp=Qt.createComponent("MyRectangle.qml")
      comp.createObject(page,{"id":"pippo","color":"yellow","width":50})

    }


    Page{
     id: page
     anchors.fill: parent


     Button{


         x:200
         height: 50
         width: 50
         onClicked:{

            // i want to set color of the rectangle tha i have created
         }
       }

    }

}

MyRectangle 是我的自定义 qml 对象。

Rectangle {
    id:pippo
    color:"red"
    width:30
    height: 30
}

标签: qtqml

解决方案


您必须使用创建的对象来执行此操作,并且您可以获得createObject()返回的内容:

Window {
    id:win
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    property var pippo_object: null
    Component.onCompleted: {
        var comp=Qt.createComponent("MyRectangle.qml")
        pippo_object = comp.createObject(page, {
                                            "id":"pippo",
                                            "color":"yellow",
                                            "width":50
                                        })
    }
    Page{
        id: page
        anchors.fill: parent
        Button{
            x:200
            height: 50
            width: 50
            onClicked:{
                if(pippo_object!==null)
                    pippo_object.color = Qt.rgba(Math.random(), 
                                                Math.random(), 
                                                Math.random(),
                                                1)
            }
        }
    }
}

推荐阅读