6

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!

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
Ispas Claudiu
  • 1,890
  • 2
  • 28
  • 54
  • You can probably exploit `highlightRangeMode` or the `contentY` properties. Anyhow, why do you want to know that? What's the specific result you want to achieve? – BaCaRoZzo Jun 25 '15 at 12:50
  • I want to hold the list view at the current position even if the model is changed. Now, if my model is changed the list jumps at the beginning. – Ispas Claudiu Jun 25 '15 at 13:06
  • Oh, the problem from the other question. Maybe `highlightRangeMode` could be of help. – BaCaRoZzo Jun 25 '15 at 13:16
  • Ok, take a look at this [example](http://pastebin.com/PVsUKyfy). The possible drawback of this approach is that the list moves strinctly within the highlight range which means that, when at the end, only the last `Item` is visible at the top of the list. See if the approach fits with your use case. – BaCaRoZzo Jun 25 '15 at 13:41

4 Answers4

4

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

Denis K.
  • 56
  • 4
1

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

iSplasher
  • 441
  • 5
  • 7
0

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.

skypjack
  • 49,335
  • 19
  • 95
  • 187
0

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)))
user3496846
  • 1,627
  • 3
  • 16
  • 28