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

Qt Quick自定义VMComboBox调用positionViewAtIndex参数相同结果不一致问题

问题原因
  1. 索引越界:Qt Quick的ListView索引从0开始计数,你当前100条数据的合法索引范围是0~99,而你在scroll函数中用Math.ceil计算得到的itemThatShouldBeVisble在滚动到最底部时取值为100,属于无效索引,positionViewAtIndex接收到无效索引时会直接静默不执行操作。
  2. 两种场景表现不一致的原因:拖动滑块时是连续触发scroll调用,在滑块接近底部、计算结果还没到100的时候,已经通过合法索引99把列表滚动到了最底部,后续传入无效索引100时列表已经处于底部位置,所以感知不到异常;而点击滚动条空白区域时是单次调用scroll,直接传入了无效索引100,列表没有被提前滚动到底部,所以出现了无响应的情况。
解决方案

只需要在计算目标索引时增加一层钳位逻辑,限制索引最大为合法的最大值vmListSize - 1即可,修改后的scroll函数代码如下:

function scroll(y){
    // Doing the scroll computations.
    var totalH = vmListSize*vmComboBox.height;
    var maxScrollY = scrollControlMA.height - scrollControl.height;
    var yPosForList = totalH*y/maxScrollY
    // 新增索引钳位,避免传入无效索引
    var itemThatShouldBeVisble = Math.min(Math.ceil(yPosForList/vmComboBox.height), vmListSize - 1)
    console.log("Item that should be visible: " + itemThatShouldBeVisble)
    listContainerListView.positionViewAtIndex(itemThatShouldBeVisble,ListView.End)
}

如果滚动手感不符合预期,也可以根据实际需求把Math.ceil替换为Math.floor或者Math.round调整计算逻辑,核心是保留索引钳位的逻辑避免越界。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:57:00