Vishnu Cyruz
Vishnu Cyruz

Reputation: 243

How to scroll list view to the current item?

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)    
                }
            }           
        }
    }

Upvotes: 4

Views: 7304

Answers (2)

Vishnu Cyruz
Vishnu Cyruz

Reputation: 243

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

source_list.positionViewAtIndex(index,ListView.Center);

The animation correctly worked.

Upvotes: 4

Kevin Krammer
Kevin Krammer

Reputation: 5207

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
}

Upvotes: 5

Related Questions