kettle
kettle

Reputation: 460

How do I construct a Qt Quick object from QML JavaScript?

This seems trivial, but I can't find the answer anywhere on the internet.

I have some QML code, and in that I have some JavaScript code that enumerates through an array and creates a button for each item in the array. I need to be able to initialise a Button object in that JavaScript, but running var btn = new Button() results in a type error.

How do I make a Qt Quick object at runtime?

Upvotes: 0

Views: 160

Answers (1)

fallerd
fallerd

Reputation: 1738

Qml affords many ways to do this.

Use a Repeater (or other model-based instantiator depending on needs, like ListView, Instantiator), whose model can be an array:

Row {
    Repeater {
        id: repeater
        delegate: Button {
            text: modelData
        }

        Component.onCompleted: repeater.model = ["button1", "button2"] // JS array
    }
}

If your array is more complex than this, you can parse your array into a ListModel:

Row {
    Repeater {
        id: repeater1
        model: ListModel { }
        delegate: Button {
            text: model.myText
        }

        Component.onCompleted: {
            let array = ["button1", "button2"]
            for (let i = 0; i < array.length; i++) {
                repeater1.model.append({myText: array[i]})
            }
        }
    }
}

As JarMan suggested, dynamically create buttons in JS (there are many ways to do this method as shown in the documentation he linked):

Row {
    Component.onCompleted: {
        let array = ["button1", "button2"]
        for (let i = 0; i < array.length; i++) {
            let newButton = buttonComponent.createObject(this, {})
            newButton.text = array[i]
        }
    }

    Component {
        id: buttonComponent

        Button { }
    }
}

All of these examples result in the same outcome:

screenshot of 2 buttons dynamically instantiated

Upvotes: 1

Related Questions