Stretching element to contain all children

Juraj Blaho picture Juraj Blaho · Jun 2, 2011 · Viewed 18.8k times · Source

How is it possible in QML to automatically stretch element so that all its childs fit in it? And how to specify spacing? For example, I would like to have a rectangle around a text. The rectangle should have some internal spacing.

If I write the following then the rectangle has a size of 0,0.

Rectangle {
    color: "gray"
    anchors.centerIn: parent;

    Text {
        text: "Hello"
    }
}

If I try to fix it by using the Column element, as suggested in How to make QML items to grow to fit contents?, then I get a column through the whole window/parent,

Column {
    anchors.centerIn: parent

    Rectangle {
        color: "gray"
        anchors.fill: parent
    }

    Text {
        anchors.centerIn: parent
        text: "Hello"
    }
}

Edit:

I have also tried to use the Flow element instead of Column, but then I got a row through the whole window/parent.

Answer

Thorbjørn Lindeijer picture Thorbjørn Lindeijer · Jun 3, 2011

You can use the childrenRect property for this:

import QtQuick 2.0

Rectangle {
    width: 320
    height: 200

    Rectangle {
        color: "BurlyWood"
        anchors.centerIn: parent
        width: childrenRect.width + 20
        height: childrenRect.height + 20

        Text {
            id: hello
            x: 10
            y: 10
            text: "Hello"
        }

        Text {
            anchors.left: hello.right
            anchors.leftMargin: 10
            anchors.top: hello.top
            text: "World"
        }
    }
}

However, note that using childrenRect in combination with using anchors.centerIn: parent in one of the direct children yields a warning about a binding loop.