如何对齐 RowLayout 中的项目

How to align items in RowLayout

我想在 RowLayout 中从左到右对齐 Rectangle。在下面的代码示例中,两个 Rectangle 共享额外的 space 而不是一个接一个地堆叠。我在 RowLayout 级别和 Rectangle 级别使用了 Layout.alignment: Qt.AlignLeft,但这两种方式都没有改变视图。

Item {
    RowLayout {
        anchors.fill: parent
        spacing: 2
        

        Rectangle {
            width: 100
            Layout.fillHeight: true
            Layout.alignment: Qt.AlignLeft

            Text {
                text: "Hello world"
            }
        }

        Rectangle {
            width: 100
            Layout.fillHeight: true
            Layout.alignment: Qt.AlignLeft

            Text {
                text: "Hello world"
            }
        }
    }
}

在下面的图片中,黑色边框表示 RowLayout,红色边框表示 Rectangle

实际

预计

有关 Layout.alignment 的文档说明:

This property allows you to specify the alignment of an item within the cell(s) it occupies.

您可以像这样简单地在末尾添加一个填充项:

RowLayout {
    anchors.fill: parent
    spacing: 2


    Rectangle {
        width: 100
        Layout.fillHeight: true
        Layout.alignment: Qt.AlignLeft
        color: 'red'

        Text {
            text: "Hello world"
        }
    }

    Rectangle {
        width: 100
        Layout.fillHeight: true
        Layout.alignment: Qt.AlignLeft
        color: 'green'

        Text {
            text: "Hello world"
        }
    }

    Item {
        Layout.fillWidth: true
    }
}

但也可以使用:

Row {
    anchors.fill: parent
    spacing: 2


    Rectangle {
        width: 100
        anchors {
            top: parent.top
            bottom: parent.bottom
        }

        color: 'red'

        Text {
            text: "Hello world"
        }
    }

    Rectangle {
        width: 100
        anchors {
            top: parent.top
            bottom: parent.bottom
        }
        color: 'green'

        Text {
            text: "Hello world"
        }
    }
}

您可以将间距值更改为负值,如下所示:

RowLayout {
    anchors.fill: parent
    spacing: -parent.width*0.6
    Rectangle {
        width: 100
        Layout.fillHeight: true
        Layout.alignment: Qt.AlignLeft
        border.width:1
        border.color:"red"
        Text {
            text: "Hello world"
        }
    }
    Rectangle {
        width: 100
        Layout.fillHeight: true
        Layout.alignment: Qt.AlignLeft
        border.width:1
        border.color:"red"
        Text {
            text: "Hello world"
        }
    }

}