【问题标题】:How to change the spacing between items in a Column or Row如何更改列或行中项目之间的间距
【发布时间】:2015-10-20 04:28:54
【问题描述】:

我在 QML 中使用 ColumnRow 类型对齐 Items。有没有办法给每个Item 提供不同的间距。大致如下:

喜欢

项目1

间距:10

项目2

间距:20

项目3

间距:40

项目4

这是我的代码:

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Rectangle{
        id: rect
        anchors.fill: parent

        Column{
            id: column
            anchors.centerIn: parent
            spacing: 10

            Row{
                id: row1
                anchors.horizontalCenter:  parent.horizontalCenter
                Rectangle{
                    width: 300
                    height: 100
                    color: "lightgreen"
                }
            }
            Row{
                id: row2
                anchors.horizontalCenter:  parent.horizontalCenter
                Rectangle{
                    width: 100
                    height: 50
                    color: "lightblue"
                }
            }
            Row{
                id: row3
                anchors.horizontalCenter:  parent.horizontalCenter
                Rectangle{
                    width: 50
                    height: 50
                    color: "green"
                }
            }
        }
    }
}

【问题讨论】:

  • 改用ColumntLayout。它具有Layout.topMargin 附加属性来设置边距(在您的情况下为顶部)以及底部、右侧和左侧。
  • @folibis 写下答案。这当然是解决问题的好方法。
  • 我同意@BaCaRoZzo 的观点。
  • @folibis 我在很多地方都在关注这个,所以我不想更改为 ColomnLayout。为此我不能使用 topmargin
  • 您可以使用“spacer”Items 来获得更细粒度的间距。不太实用,但很管用。

标签: qml qt5 qtquick2


【解决方案1】:

带有间隔项的 hacky 版本

有时我比 ColumnLayout 更喜欢这个,因为在某些情况下我不能使用 ColumnLayout(虽然目前无法准确解释原因)。 我得到它的工作如下

Column {
    Rectangle {
        // ...
    }

    Item {
        width: 1 // dummy value != 0
        height: 10
    }

    Rectangle {
        // ...
    }

    Item {
        width: 1 // dummy value != 0
        height: 20
    }

    Rectangle {
        // ...
    }
}

宽度为 0 的项目将不起作用。我建议将 Spacer_Col.qml(和 Spacer_Row 模拟)放入您的工具箱,看起来像

import QtQuick 2.8
Item {
    id: root
    property alias spacing: root.height
    width: 1 // dummy value different from 0
}

使用列布局

ColumnLayout {
    Rectangle{
        // ...
    }

    Rectangle{
        Layout.topMargin: 10
        // ...
    }

    Rectangle{
        Layout.topMargin: 20
        // ...
    }
}

【讨论】:

    【解决方案2】:

    通过嵌套你想要间隔的每个矩形,如下;

        Row {
            spacing: 20
            Rectangle { color: "red"; width: 50; height: 50 }
    
            Row {
                spacing: 50
                Rectangle { color: "green"; width: 20; height: 50 }
    
                Row {
                    spacing: 100
                    Rectangle { color: "blue"; width: 50; height: 20 }
                }
            }
        }
    

    Different spacings in a row

    【讨论】: