0

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?

1
  • 1
    You're looking for dynamic object creation. The docs are here. Commented May 28, 2021 at 13:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I just have on more question: If I want the button to resize to, say, a third of the parent's size, how could I do that?
I fixed it. It had to do with the parent widget of my buttons trying to arrange them in a weird way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.