How can I get the first visible item/index from a ListView?

5.2k views Asked by At

How can I get the first Item/index that is visible in a ListView? I looked inside the documentation and also searched a lot on the Internet but couldn't find anything. Does anyone know how to do that?

Thank you!

4

There are 4 answers

0
skypjack On

Store the selected index when it changes. Once the model changes and the index becomes -1, you can use positionViewAtIndex to restore the right position.

Here the documentation of the method.

Otherwise, you can do the same relying on the add and remove method. Obviously, it works as far as the index of the selected item changes. You can also get the index of the visible item by means of the indexAt method, but I've never used it before, even though it looks easy to use.

So, you have several methods to get the index of the visible item and you can reset the view by means of the method above mentioned.

1
iSplasher On

I know this is late but for others seeking help:

You can use the member method myView.indexAt(QPoint(0,0)) to find the first index.

I've also made a snippet to find all visible indexes in a view if you need that too: https://gist.github.com/iSplasher/8ebc42eaf9ea206b19bd

0
user3496846 On

Based on iSplasher's answer, the following works when QListView has spacing and/or has scroll by pixel:

sp = view.spacing()
first = max(view.indexAt(QPoint(sp, 0)), view.indexAt(QPoint(sp, sp * 2)))
0
Denis K. On

You should use something like that:

ListView {
        id: contacts
        model: UsersModel

        onContentYChanged: {
            var CurrentIndexAtTop = indexAt(1, contentY)
            var CurrentPropFromModel = UsersModel.get(CurrentIndexAtTop).Name
        }
}

if indexAt return -1 means not found, check this if need! contentY - it is a property of ListView, that return current position top Y-coord of ViewList window on flickable grid ListView.

see documentation for more details http://doc.qt.io/qt-5/qml-qtquick-listview.html#indexAt-method