Steve
Steve

Reputation: 596

How to dynamically create objects with variables?

I'm having trouble trying to generate objects in QML using Javascript to create them dynamically.

The code I am trying to use is this

Grid {
    id: numbers
    anchors.centerIn: parent
    columns: 3
    spacing: 2
    function createNumbers(){
        var component = Qt.createComponent("Button.qml");
        for(var i=1; i<37; i++){
            component.createObject(numbers)
        }
    }
    Component.onCompleted: createNumbers()
}

Which works fine, however I want to include variables to make them each different, so that when I pass the information to Button.qml it sets the following

property string text: "1"
property string id: "button1"

I can't figure it out, any help would be great, thanks guys.

Upvotes: 4

Views: 2109

Answers (1)

TheHuge_
TheHuge_

Reputation: 1039

Here's the documentation of method Component.createObject.

As you can see you can set the parameters of the new object using the second optional parameter of the function. In your case it would be:

component.createObject(numbers, {"text": "1", "id": "button1"});

Upvotes: 3

Related Questions