Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i set one or more properties of an object created dynamically?

Tags:

qt

qml

my question is very simple. If i have created a qml component dynamically , how can i set its properties ?
In this my example i want to change the color when i click on button element

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 is a my custom qml object.

Rectangle {
    id:pippo
    color:"red"
    width:30
    height: 30
}
like image 694
pablodepas87 Avatar asked Jan 25 '26 10:01

pablodepas87


1 Answers

You have to do it using the created object and that you can get with what createObject() returns:

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)
            }
        }
    }
}
like image 196
eyllanesc Avatar answered Jan 27 '26 01:01

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!