user140053
user140053

Reputation:

Dynamic creation of a button in QML

With qt 5.2, I'm trying to add dynamically a simple button like this :

ApplicationWindow
{
    id: appWindow

    width: 640
    height: 420
    minimumHeight: 400
    minimumWidth: 600

    function addButton() {

        var obj = Qt.createComponent("Button.qml");

        if (obj.status == obj.Ready)
        {
            var button = obj.createObject(appWindow);
            button.color = "red";
            button.width=50;
            button.height=80;
            button.x=50; button.y=50;
           }
     }


    Button {
        anchors.centerIn: parent;
        text: "ok";

        onClicked: {
            addButton();
        }
    } ...

But just after the createComponent I always get :

QQmlComponent: Component is not ready

What's wrong ?

Upvotes: 3

Views: 4126

Answers (1)

TheBootroo
TheBootroo

Reputation: 7518

To be sure that the component will be ready, the best way is simply to declare it inside the QML part, inside a Component object, so that it'll be preloaded at same time as the rest of the file :

ApplicationWindow {
    id: appWindow;

    Component {
        id: myButton;

        Button { }
    }

    function addButton () {
        var button = myButton.createObject (appWindow, {
                                                "color"  : "red",
                                                "width"  : 50,
                                                "height" : 80,
                                                "x"      : 50, 
                                                "y"      : 50
                                            });
    }

    ...
}

As you can see, I also took the liberty to show you the syntax to create the object directly with the good properties in one shot, instead of setting them manually in the old school way. Much more clean code and probably more performant.

Upvotes: 2

Related Questions