如何在RowLayout中对齐项目

时间:2017-11-08 18:20:18

标签: qt qml qt5 qtquick2

我希望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

实际

Acual layout

预期

Expected layout

2 个答案:

答案 0 :(得分:5)

文档说明了Layout.alignment

  

此属性允许您指定项目占据的单元格内的对齐方式。

您可以在最后添加填充项,如下所示:

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

答案 1 :(得分:-1)

您可以将间距值更改为下面的负数:

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

}
相关问题