qtqmlqtquick2

Flow layout with centered content


I have a row with items which should stack when the window width gets too small for displaying all items in a row, as shown in the following sketch:

enter image description here

The Flow component stacks the items but they are not centered but aligned on the left or right side:

Flow {
    Item {}
    Item {}
    Item {}
    Item {}
    Item {}
}

Is there a built-in way in QML to make the flow centered?


Solution

  • Well there is no built-in way but I found a workaround to do it.

    The idea is simple, since Flow is already an Item it has anchors.leftMargin and anchors.rightMargin. So if we can calculate, how many elements are inside the row of the Flow then we are able to calculate the left and right margins. So we can center in.

    Here it is a simple code,

            Flow {
            property int rowCount: parent.width / (elements.itemAt(0).width + spacing)
            property int rowWidth: rowCount * elements.itemAt(0).width + (rowCount - 1) * spacing
            property int mar: (parent.width - rowWidth) / 2
            
            anchors {
                fill: parent
                leftMargin: mar
                rightMargin: mar
            }
            
            spacing: 6
            Repeater {
                id: elements
                model: 5
                Rectangle {
                    color: "#aa6666"
                    width: 100; height: 100
                }
            }