NathanPB
NathanPB

Reputation: 745

How to align items in a ListView in QtQuick

I have the following horizontal list:

BulletsListDelegate.qml

import QtQuick 2.0

Rectangle {
    width: 8
    height: 8

    color: "#808080"
    radius: width * 0.5
}

main.qml

import QtQuick 2.0

Item {
    width: 256
    height: 256

    ListModel {
        id: bulletsListModel

        ListElement {
            a: 'example'
        }
        ListElement {
            a: 'example'
        }
        ...
    }

    ListView {
        id: bulletsList

        spacing: 8
        orientation: ListView.Horizontal

        delegate: BulletsListDelegate {}
        model: bulletsListModel

        anchors.bottom: parent.bottom
        width: parent.width
    }
}

And the elements are shown like this (they are the grey bullets)

buttons

I want them to show in the horizontal center of the black box above them (its parent).

Is there any form of centralize or justify the items of the list?

Upvotes: 2

Views: 1830

Answers (2)

NathanPB
NathanPB

Reputation: 745

André's answer suggested me to use Repeater and Rows instead of ListView, and it completely solved my problem. But... didn't find a way to align an actual ListView yet.

Row {

    spacing: 8

    Repeater {
        id: bulletsRepeater

        model: 5

        BulletsDelegate { }
    }

    anchors.bottom: parent.bottom
    anchors.horizontalCenter: parent.horizontalCenter
}

Upvotes: 0

André
André

Reputation: 590

So, if I understand your question correctly, you want to have alignment for instances of your items in a ListView. Using a ListView, that is not so easy to achieve. If you have an uneven number of items, you can do it by using preferredHighlightBegin and preferredHighlightEnd to have a 1-item sized region in the center of your ListView, and then setting hightlightRangeMode to ListView.StrictlyEnforceRange. You can set the currentIndex to point to index so that the middle item will be considered current. That puts it within the range you defined, and thus in the center. That does not work when you have an even number of items though, so it's a hack with limited value.

My question is: do the items have to be positioned using a ListView? It looks like you don't actually need much of the functionality of the ListView at all? If you don't need the other features from ListView (like scrolling), you can just use a Repeater instead. That allows you to simply put the items in a Row positioner, which you can width of count*(delegateWidth+spacing)-spacing and a height equal to your delegate height. Then, you can use acnhors to position the Row centered to whatever you like.

Upvotes: 2

Related Questions