Stretching element to contain all children

21,201

Solution 1

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.

Solution 2

Setting the width and height manually works, but is a little ugly:

Rectangle {
    color: "gray"
    width: label.width+20
    height: label.height+20
    anchors.centerIn: parent

    Text {
        id: label
        anchors.centerIn: parent
        text: "Hello"
    }
}
Share:
21,201
Juraj Blaho
Author by

Juraj Blaho

Updated on July 18, 2021

Comments

  • Juraj Blaho
    Juraj Blaho almost 3 years

    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.

  • ManuelSchneid3r
    ManuelSchneid3r over 8 years
    main.qml:6: ReferenceError: childrenRect is not defined. What is the problem? Qt 5.3, QtQuick 2.3
  • Thorbjørn Lindeijer
    Thorbjørn Lindeijer over 8 years
    @ManuelSchneid3r Hmm, I can't reproduce your problem. I just tried it with Qt 5.5, running the above code with qmlscene after changing the import to QtQuick 2.3. Worked fine.
  • ManuelSchneid3r
    ManuelSchneid3r over 8 years
    The problem was that i tried this in the Windowscope. There, childrenRect is not defined.
  • Thorbjørn Lindeijer
    Thorbjørn Lindeijer over 8 years
    Ah, indeed, because Window is not an Item. So I guess you'd need to use an explicit root item that is a child of the window.