0
votes

I'm trying to understand how anchors work in QML (Qt Quick 2.0). I've got a simple Item like this:

AddButton.qml:

Item {

    Button {
        text: "ADD"
        width: 100
        height: 50
    }

}

Which I add to the main QML file like this:

main.qml:

Item {
    id: root
    width: 800
    height: 600

    AddButton {
        id: addButton
    }

}

This works fine. However, as soon as I try to put the button in the bottom right corner using anchors, the button disappears:

main.qml:

Item {

    .....

    AddButton {
        id: addButton
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

}

It only comes back if I set a width and height at the main QML file level:

main.qml:

Item {

    .....

    AddButton {
        id: addButton
        width: 100
        height: 50
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

}

So I'm wondering, why does the button disappear when I set the anchors? And is there any way to make it work without setting the width and height in the main QML file (basically to make it use whatever size is set in AddButton.qml?)

1

1 Answers

4
votes

The problem is that the encapsulating Item has not an explicit width height. In this case the engine refers to the "natural" witdh/height, i.e. the implicitWidth/implicitHeight properties. Such properties happen to be zero in most cases, even in this specific case. Hence, your custom type has zero dimension. Therefore the AddButton.anchors.bottom is in fact at the very top of the encapsulated Button, which in turn protrudes the encapsulating Item

There are two things about this:

You don't need to encapsulate the Button with an Item unless you want to hide the internals of the Button.

If the latter is your desire, try this:

Item {
    width: 100 //give the object a dimension!
    height: 50

    Button {
        text: "ADD"
        anchors.fill: parent
    }
}

Now you can anchor it, and it won't be positionated somewhere else.