如何在 RowLayout 中对齐项目

问题描述 投票:0回答:3

我想将

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

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
s。

实际

预计

qt qml qt5 qtquick2
3个回答
16
投票

文档说明了有关

Layout.alignment

此属性允许您指定项目在其占据的 cell(s) 内的对齐方式。

您可以简单地在末尾添加一个填充项,如下所示:

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

0
投票

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

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

}

0
投票

根据布局文档,您不应该对布局内的项目使用宽度属性。相反,如果需要,您应该使用 Layout.preferredWidth/Height 和 min/max

© www.soinside.com 2019 - 2024. All rights reserved.