首页 文章

如何为未指定大小的qml项设置背景?

提问于
浏览
1

将背景设置为qml项目的最简单方法是只有一个子矩形,其锚点完全填满父项:

Item
{
    width: 320
    height: 240
    Rectangle
    {
        id: background
        anchors.fill: parent
        color: "blue"
    }

    // other items

}

但是,这仅适用于父项具有定义的大小(宽度和高度) .

我想有一个没有为它定义固定大小的容器 . 孩子们将有固定的大小,但是当孩子们可以动态地改变他们的大小时,我希望父容器能够成长和缩小以适应 .

如果我按顺序锚定孩子,除了背景之外,一切都很好 .

关于类似的主题有a question a while ago,但问题是所有的孩子都是重叠而不是并排显示 . 这不是我的问题,因为将它们锚定在序列中(或使用 RowLayout )会正确显示它们 .

Item
{
    // I don't want a fixed size here

    Rectangle
    {
        id: background
        anchors.fill: parent
        color: "blue"
    }


    RowLayout
    {
        anchors.fill: parent

        Item
        {
            id: child1
            anchors.left = parent.left
            anchors.top: parent.top

            width:100
            height:100
        }

        Item
        {
            id: child2
            anchors.left = child1.right
            anchors.top: parent.top

            width:120
            height:120
        }

        // further children

    }

}

但是,不显示背景,因为父级没有定义的大小,尽管所有子级都有固定的大小,如果我指定最后一个子级的右锚作为父级的权限,它仍然是显示正确 . 我想这意味着渲染器应该知道父级的大小 .

(如果我使用 ItemRectangle 而不是 RowLayout ,则没有任何变化 . 实际上,当使用 RowLayout 时我可以省略顺序锚定,但这不会改变我的背景问题)

1 回答

  • 3

    首先,如果您希望容器具有背景,则必须将 Rectangle 设为根,而不是将 Rectangle 放在 Item 中 . 此外,您不能在 Layout 中使用锚点,因为 Layout 根据自己的规则管理其子项的布局 .

    至于这个问题,你可以使用 Layout ,因为它增长到包含它的所有子节点,如下面的代码所示:

    Rectangle {
        anchors.centerIn: parent
        width: grid.width + 10
        height: grid.height + 10
        color: "orange"
        GridLayout {
            anchors.centerIn: parent
            id: grid
            columns: 5
            rowSpacing: 2
            columnSpacing: 2
            Repeater {
                model: 10 + Math.round(Math.random() * 50)
                Rectangle {
                    width: 20 + Math.round(Math.random() * 50)
                    height: 20 + Math.round(Math.random() * 50)
                    border.width: 1
                    border.color: "#999"
                }
            }
        }
    }
    

    另一个解决方案是使用 Item.childrenRect

    Rectangle {
        id: container
        anchors.centerIn: parent
        width: childrenRect.x + childrenRect.width;
        height: childrenRect.y + childrenRect.height;
        border.width: 1
        border.color: "#999"
        Repeater {
            model: 10 + Math.round(Math.random() * 50)
            Rectangle {
                x: Math.round(Math.random() * 500)
                y: Math.round(Math.random() * 500)
                width: 100 + Math.round(Math.random() * 100)
                height: 100 + Math.round(Math.random() * 100)
                color: Qt.rgba(Math.random(),Math.random(),Math.random(),1)
            }
        }
    }
    

相关问题