qml

Flickable scrollbar position always initialized to zero


Apologies in advance for not being able to provide a working example.

I have a QML Flickable whose components are a repeater that spawns a vertical column of radio buttons. I understand the default behavior of the Flickable is to set it's scrollbar position to zero. What I'd like to do is programatically scroll down to the currently checked radio button. The problem is that every time I set the ScrollBar.position or the property Flickable.contentY to anything other than zero it will immediately get set back to zero.

After initialization is completed I can programmatically control the scrollbar without an issue. However, this is not what I need.

I have tried moving the ScrollBar by setting the position/contentY values in the callback Component.onCompleted for the flickable, the scrollbar, the parent, and the parent's parent with no luck. Below is basically how I have my Flickable set up. Again, I apologize that I am unable to provide a working example.

Rectangle
{
  anchors.fill: parent
  property var fileNames: []

  onFileNamesChanged:
  {
    repeater.model = fileNames
  }

  Flickable
  {
    id: flickable
    anchors.fill: parent
    clip: true

    ScrollBar.veritical: ScrollBar
    {
      parent: flickable.parent
      anchors.top: flickable.top
      anchors.left: flickable.left
      anchors.bottom: flickable.bottom
      anchors.leftMargin: 4

      contentItem: Rectangle
      {
        radius: 5
        implicitWidth: 5
        color: "grey"
      }
    }
    Column
    {
      id: flickableColumn
      width: parent.width
      spacing: 5

      Repeater
      {
        id: repeater
        delegate: Column
        {
          id: delegateColumn
          width: flickableColumn.width
          spacing: flickableColumn.spacing

          RadioButton {/** some stuff **/}
          Rectangle{/** set up as a divider bar **/}
        }
      }
   }
}

I have a console.log command set up in the ScrollBar's callback to onPositionChanged. The last two logs are: CHANGING SCROLLBAR POSITION 0.18181818181818183 // <-- Correct position

CHANGING SCROLLBAR POSITION 0


Solution

  • [EDIT: Applied smr's feedback]

    A couple improvements:

    ListView {
        anchors.fill: parent
        model: "abcdefghijklmopqrstuvwxyz".split("").map(ch => `filename-${ch}.txt`)
        clip: true
        delegate: Column {
            RadioButton {
                text: modelData
                checked: listView.currentIndex == index
                onToggled: listView.currentIndex = index
            }
            Rectangle { height: 1; width: parent.width; color: "black" }
        }
        highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
        highlightRangeMode: ListView.ApplyRange
        currentIndex: 5
        ScrollBar.vertical: ScrollBar { width: 20; policy: ScrollBar.AlwaysOn }
    }
    

    You can Try it Online!