QML Listview space items to fill width

Viewed 613

I have a ListView (horizontal orientation) in my qml containing some fixed-size elements. I want items to be spaced out to fill the entiew width of ListView element. So if there are less elements I want them to be spaced out more. Basically what I need is exactly like Layout.fillWidth = true property of RowLayout but for ListView.

I can count how many items I have, then subtract total items width from ListView width, divide by items count and assign the spacing but it seems too silly to do. Is there a way to do this automatically like in RowLayout?

enter image description here

Or maybe I need to use something different from ListView for this? Something like RowLayout but that I can assign my list data model to?

1 Answers

You can accomplish what you want with a ListView, you just need to adjust the spacing dynamically based on how many delegates you have. This example will break down if your delegates are differently-sized (as this is based only on the width of the first delegate), or if the delegates cumulatively exceed the width of the ListView.

ListView {
    width: 500
    orientation: Qt.Horizontal
    model: 6
    spacing: {
        if (count > 0) {
            return (width - (itemAtIndex(0).width * count))/(count - 1)
        } else {
            return 0
        }
    }

    delegate: Rectangle {
        implicitHeight: 50
        implicitWidth: 50
        color: "red"
        border.width: 1
    }
}

6 delegates 4 delegates

ListView may not be the most appropriate container for this task. I say this because it has a built in ScrollView and other behaviors that it sounds like you don't need. If all you need is a simple row of a few identically-sized delegates, I agree with scopchanov and believe that a Repeater inside a RowLayout would be the best option. Here is a simple example:

RowLayout {
    width: 500

    Repeater {
        model: 6
        delegate: Rectangle {
            implicitHeight: 50
            implicitWidth: 50
            color: "tomato"
            border.width: 1
            Layout.alignment: Qt.AlignHCenter // must be set to align the rectangles within their empty space
        }
    }
}

6 delegates 4 delegates

You may notice that this introduces gaps to the left and right, if these gaps are unacceptable, you may need to set the spacing on the RowLayout in the same manner as the ListView example instead.

Related