Flow layout with centered content

蹲街弑〆低调 提交于 2019-12-23 09:25:39

问题


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:

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?


回答1:


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 is inside the row of theFlow 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
            }
        }



回答2:


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

No.

You can do the maths to check if the last "row" in the Flow is not full, and then add some spacer items to the left and right of the items in that row. You'd have to use some C++ though, probably; namely QQuickItem::stackBefore() and QQuickItem::stackAfter() to reposition the spacer items within the list of children of the Flow. The width of each spacer item would be half of the remaining space within that row. It's not pretty, but it should work.




回答3:


I don't think there is any built-in way to do so. You have to make your own element.



来源:https://stackoverflow.com/questions/33462117/flow-layout-with-centered-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!