Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretching element to contain all children

Tags:

qt

qml

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.

like image 564
Juraj Blaho Avatar asked Jun 02 '11 09:06

Juraj Blaho


2 Answers

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.

like image 89
Thorbjørn Lindeijer Avatar answered Nov 14 '22 20:11

Thorbjørn Lindeijer


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"
    }
}
like image 25
Juraj Blaho Avatar answered Nov 14 '22 20:11

Juraj Blaho