Listview optional autoscroll
-
Hello,
I have a QML ListView populated by regular additions of strings in a QStringList. (Using Qt 6.7)
I made it autoscroll to the last entry like this, and it works fine:ListView { ... onCountChanged: Qt.callLater( positionViewAtEnd ) }
However I would like the autoscroll behaviour to be optional, and I've added a checkbox in my UI, that I now check before calling the above function, like this:
ListView { ... onCountChanged: { if ( followCheckbox.checked ) { Qt.callLater( positionViewAtEnd ) } }
It works when it is checked, but when not checked, I would expect the ListView not to move, but it scrolls to the top instead!
Could someone give me a clue as to why this is happening, and how to implement what I'm trying to do differently if there is a better way?
Thanks in advance, -
The issue is likely rooted in a QStringList not being a real QAbstractItemModel. Changes to the emulated models, such as a string list or integer, result in a new model rather than a change to the previously created emulated model. Each time a new, non-empty model is assigned to the view, it's currentIndex is reset to 0.
-
The issue you're encountering is likely due to the positionViewAtEnd function being called by default when the checkbox is not checked. This causes the ListView to move, potentially resetting its position.
To fix this, you can store the current position of the ListView before making any changes and then restore it if the autoscroll is disabled. Here’s an alternative approach:
ListView {
id: listView
...
property int savedPosition: -1onCountChanged: { if (followCheckbox.checked) { Qt.callLater(positionViewAtEnd) } else { if (savedPosition >= 0) { listView.contentY = savedPosition } } } onContentYChanged: { if (!followCheckbox.checked) { savedPosition = listView.contentY } }
}
savedPosition: Stores the current scroll position of the ListView.
onCountChanged: Checks if the autoscroll is enabled. If so, it scrolls to the end; otherwise, it restores the saved position.
onContentYChanged: Updates the saved position whenever the contentY changes, but only if the autoscroll is disabled.
This should prevent the ListView from unexpectedly scrolling to the top when the checkbox is unchecked. -