Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center QML ListView highlighted item

Tags:

listview

qt

qt5

qml

Current behavior

In the picture Test, Test 1 and Test 2 are in the ListView. In this case Test element is highlighted. How can I modify view behavior to ensure that current (highlighted) item stays always in the middle of the list? What I want to achieve is represented in the following picture:

Desired behavior

like image 321
gmlt.A Avatar asked Apr 16 '15 05:04

gmlt.A


1 Answers

You just need highlightRangeMode with preferredHighlightBegin and preferredHighlightEnd. From the documentation:

These properties affect the position of the current item when the list is scrolled. For example, if the currently selected item should stay in the middle of the list when the view is scrolled, set the preferredHighlightBegin and preferredHighlightEnd values to the top and bottom coordinates of where the middle item would be. If the currentItem is changed programmatically, the list will automatically scroll so that the current item is in the middle of the view. Furthermore, the behavior of the current item index will occur whether or not a highlight exists.

Here is a full example of an horizontal ListView with the current item positioned at the center.

import QtQuick 2.4
import QtQuick.Window 2.2

Window {
    width: 300
    height: 150
    visible: true

    ListView {
        anchors.fill: parent
        spacing: 5

        model: 20

        delegate:
            Rectangle {
            width: 30
            color: ListView.view.currentIndex === index ? "red" : "steelblue"

            height: ListView.view.height
            Text {
                anchors.centerIn: parent
                text: index
                font.pixelSize: 20
            }
        }

        orientation: Qt.Horizontal
        preferredHighlightBegin: 150 - 15
        preferredHighlightEnd: 150 + 15
        highlightRangeMode: ListView.StrictlyEnforceRange
    }
}
like image 50
BaCaRoZzo Avatar answered Sep 22 '22 22:09

BaCaRoZzo