30

QML中如何自动拉伸元素以使其所有子元素都适合它?以及如何指定间距?例如,我想在文本周围有一个矩形。矩形应该有一些内部间距。

如果我写以下内容,则矩形的大小为 0,0。

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

    Text {
        text: "Hello"
    }
}

如果我尝试使用该Column元素来修复它,如如何使 QML 项目增长以适应内容?,然后我通过整个窗口/父级得到一列,

Column {
    anchors.centerIn: parent

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

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

编辑:

我也尝试使用该Flow元素而不是Column,但后来我在整个窗口/父级中获得了一行。

4

3 回答 3

47

您可以为此使用该childrenRect属性:

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"
        }
    }
}

但是,请注意,将 usingchildrenRect与 using anchors.centerIn: parentin 其中一个直接子项结合使用会产生有关绑定循环的警告。

于 2011-06-03T08:42:34.960 回答
8

设置widthandheight手动工作,但有点难看:

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

    Text {
        id: label
        anchors.centerIn: parent
        text: "Hello"
    }
}
于 2011-06-02T10:38:04.843 回答
0

我认为使用chilrenRect属性是不够的(正如 Thorbjørn Lindeijer 所建议的那样)。它不会自动考虑子(ren)元素的所有各种边距。如果后者发生变化,根矩形不会自动调整其大小。我个人提出了以下解决方案:

Rectangle {
    color: "white"
    implicitWidth: row.implicitWidth + extraLeft + extraRight
    implicitHeight: row.implicitHeight + extraTop + extraBottom
    
    property int extraMargin: row.anchors.margins ? row.anchors.margins : 0
    property int extraTop: row.anchors.topMargin ? row.anchors.topMargin : extraMargin
    property int extraBottom: row.anchors.bottomMargin ? row.anchors.bottomMargin : extraMargin
    property int extraLeft: row.anchors.leftMargin ? row.anchors.leftMargin : extraMargin
    property int extraRight: row.anchors.rightMargin ? row.anchors.rightMargin : extraMargin
    
    
    RowLayout {
        id: row
        spacing: 50
        anchors.fill:parent
        anchors.margins: 50
        anchors.leftMargin: 100
        
        Label {
            text: "hello"
        }
        Label {
            text: "world"
        }
    }
}
于 2021-07-18T07:43:23.570 回答