Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll list view to the current item?

Tags:

qt

qml

qtquick2

I have a list view. If i click on a cell, that specific cell need to move to the center with a small scrolling animation. With my code, the clicked cell will comes to the center without any animation.

Is it possible to add animation for that ?

Am putting my code below :

    ListView {
        id: source_list
        width: 1080
        height: 480
        spacing: 50
        model: mediaSongsModel
        delegate: mediaSongsDelegate
        focus: true
        interactive: true
        clip: true
        highlightMoveDuration: 50
        snapMode: ListView.SnapToItem
        boundsBehavior:Flickable.StopAtBounds
        preferredHighlightBegin: 260/scaleFactor
        preferredHighlightEnd: 260/scaleFactor
        highlightRangeMode: ListView.StrictlyEnforceRange
    }                

    Component {
        id: mediaSongsDelegate
        Item {
            id: wrapper
            width: 1080
            height: 200

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    source_list.currentIndex = index
                    source_list.positionViewAtIndex(index,ListView.Center)    
                }
            }           
        }
    }
like image 259
Vishnu Cyruz Avatar asked Feb 05 '23 15:02

Vishnu Cyruz


2 Answers

If the current item should always be in the center or within a specific are of the view, then you can use the preferredHighlightBegin and preferredHightlightEnd properties to define that area.

The value of highlightRangeMode controls if and if yes, how strictly this applies. E.g. if the first item is the current item and the value is StriclyEnforeRange then the item will be within the specified area even if that means scrolling further up than a normal "scroll to top" would.

Something like that should work

ListView {
    preferredHighlightBegin: height / 2 - 100 // 100 being item height / 2
    preferredHighlightEnd: height / 2 + 100 // 100 being item height / 2
    highlightRangeMode: ListView.StrictlyEnforceRange
}
like image 65
Kevin Krammer Avatar answered Feb 08 '23 15:02

Kevin Krammer


I've solved my issue by removing the following line of code:

source_list.positionViewAtIndex(index,ListView.Center);

The animation correctly worked.

like image 32
Vishnu Cyruz Avatar answered Feb 08 '23 15:02

Vishnu Cyruz