You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QML Flickable自动滚动至ListView选中项位置异常问题

QML Flickable自动滚动至ListView选中项位置偏移问题

我在QML中尝试实现Flickable自动滚动到ListView的选中项,已经编写逻辑计算目标项位置并设置Flickable的contentY属性,但滚动位置始终偏在选中项下方。相关代码及日志信息如下:

选中项索引定义

// 从模型获取的有效选中项索引
property var selectedServerIndex: ServersModel.getDefaultServerIndex()

Flickable代码

Flickable {
    id: serversContainer

    anchors.top: serversMenuHeader.bottom
    anchors.right: parent.right
    anchors.left: parent.left
    anchors.topMargin: 16

    contentHeight: col.height + col.anchors.bottomMargin
    implicitHeight: parent.height - serversMenuHeader.implicitHeight
    clip: true

    function autoScroll() {
        const eachListitemHeight = serversMenuContent.contentItem.height / serversMenuContent.count
        const totalItemsHeight = selectedServerIndex * eachListitemHeight
        contentY = totalItemsHeight - (implicitHeight / 2)
        console.log(eachListitemHeight)
        console.log(totalItemsHeight)
        console.log(implicitHeight)
        console.log(contentY)
    }
    Component.onCompleted: autoScroll()

    ScrollBar.vertical: ScrollBar {
        id: scrollBar
        policy: serversContainer.height >= serversContainer.contentHeight ? ScrollBar.AlwaysOff : ScrollBar.AlwaysOn
    }
}

ListView相关代码

Column {
    id: col
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottomMargin: 32

    spacing: 16

    ButtonGroup {
        id: serversRadioButtonGroup
    }

    ListView {
        id: serversMenuContent
        width: parent.width
        height: serversMenuContent.contentItem.height

        model: ServersModel
        currentIndex: ServersModel.defaultIndex

        Connections {
            target: ServersModel
            function onDefaultServerIndexChanged(serverIndex) {
                serversMenuContent.currentIndex = serverIndex
            }
        }

        clip: true
        interactive: true

        delegate: Item {
            id: menuContentDelegate

            property variant delegateData: model

            implicitWidth: serversMenuContent.width
            implicitHeight: serverRadioButtonContent.implicitHeight

            ColumnLayout {
                id: serverRadioButtonContent

                anchors.fill: parent
                anchors.rightMargin: 16
                anchors.leftMargin: 16

                spacing: 0
        }
    }
}

日志信息

日志变量说明:

  1. 第一个值:ListView中每个项的高度
  2. 第二个值:选中项上方所有项的总高度
  3. 第三个值:Flickable的implicitHeight
  4. 第四个值:计算后设置的contentY值
qml: 100 // 正确
qml: 1900 // 正确,选中项为40项中的第20项
qml: 335.20000000000005 // Flickable的implicitHeight
qml: 1732.4 // contentY被设置为该值

内容的提问来源于stack exchange,提问作者Nizuko HattoRi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:52:27