关于qml:如何更改列或行中项目之间的间距

How to change the spacing between items in a Column or Row

我在QML中使用ColumnRow类型对齐Item。 有什么办法可以给每个Item不同的间距。 遵循以下内容:

喜欢:

项目1

间距:10

item2

间距:20

项目3

间距:40

项目4

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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"
                }
            }
        }
    }
}


带有间隔项的hacky版本

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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类似物)放入工具箱,看起来像

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

使用ColumnLayout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ColumnLayout {
    Rectangle{
        // ...
    }

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    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 }
            }
        }
    }

连续不同的间距