Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

qt5

qml

qtquick2

I am aligning Items using Column and Row types in QML. Is there any way to give different spacing to each Item. Something along the line of the following:

like:

item1

spacing:10

item2

spacing:20

item3

spacing:40

item4

here is my code:

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"
                }
            }
        }
    }
}
like image 238
Jeggu Avatar asked Oct 20 '15 04:10

Jeggu


1 Answers

The hacky version with spacer Items

Sometimes I prefer this over ColumnLayout since in some situations I just can't use ColumnLayout (can't explain exactly why though at the moment). I get it working as follows

Column {
    Rectangle {
        // ...
    }

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

    Rectangle {
        // ...
    }

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

    Rectangle {
        // ...
    }
}

An Item of width 0 won't work. I suggest putting a Spacer_Col.qml (and Spacer_Row analog) into you Toolbox, looking something like

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

Using ColumnLayout

ColumnLayout {
    Rectangle{
        // ...
    }

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

    Rectangle{
        Layout.topMargin: 20
        // ...
    }
}
like image 76
yau Avatar answered Sep 27 '22 18:09

yau