A Button as a Component


In the previous posts, we always used only one qml-file. No it’s time to split it up and create qml-components.

We take our simple Button example:

import Qt 4.6

Rectangle {
    width: 200; height: 200

    Rectangle {
        id: button
        color: "red"
        width: 96; height: 24; anchors.centerIn: parent
        MouseRegion {
            anchors.fill: parent;
            onClicked: console.log("clicked()")
        }
    }
}

And extract the button releated component from it and place this code into a file named SimpleButton.qml:

import Qt 4.6

Rectangle {
    id: button
    color: "red"
    width: 96; height: 24; anchors.centerIn: parent
    MouseRegion {
        anchors.fill: parent;
        onClicked: console.log("clicked()")
    }
}

As you see, I simply removed the outer 200×200 rectangle as this is not really part of the button component.

And now in another qml-file in the same folder I use now the SimpleButton component:

import Qt 4.6

Rectangle {
    width: 200; height: 200
    SimpleButton {  color: "blue" }
}

Here I just instantiate the SimpleButton component and override the color attribute to blue.

That’s all. Components can not only be loaded locally it’s also possible to load them over a network. They can also be combined into modules.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s