Positioning a ScrollView to a particluar item
-
How do you go about setting a ScrollView to the location of a particular item attached to it in Qt 6.5.x?
I've got a long user-interface in multiple QML files that I attach to a ScrollView. I want to be able to automagically scroll to a TextArea when the user clicks in it so that it snaps to the top of the view so that it doesn't get blocked by the virtual keyboard on a phone.All of the Google references on the subject make use of things in Qt 5 that are no longer accessible under Qt 6.5.x e.g. the Flickable. Yes, I can get at an attached scroll bar but that has a range of 0.0 to 1.0-size so I'd have to come up with a way of figuring out where in that range the TextArea would be.
-
So, one way to do this is to set contentItem to a Flickable. Then you can set contentY to the y position of the item you want. But that isn't easy to get especially if you have several embedded qml files with an arbitrary number of totally different user-interface elements in there. How one iterates through a list of child Items to get to the one you're want is a mystery.
-
This works for me with Qt 6.5.6:
import QtQuick import QtQuick.Controls Window { width: 640 height: 480 visible: true property Item targetItem: sv.contentChildren[0].children[25] property real targetPosition: targetItem.y / sv.contentHeight ScrollView { id: sv Column { Repeater { model: 100 delegate: Text { text: index } } } } Button { id: button anchors.right: parent.right text: "scroll to " + targetItem.text onClicked: sv.ScrollBar.vertical.position = targetPosition } }