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

Qt 5.15中使用自定义ScrollBar时默认滚动条未消失问题

解决Qt 5.15 ScrollView自定义滚动条后默认滚动条残留问题

解决这个问题的核心是彻底关闭ScrollView自带的默认垂直滚动条,同时调整自定义滚动条的布局逻辑,具体操作如下:

  • 给ScrollView添加verticalScrollBarPolicy: Qt.ScrollBarAlwaysOff属性,直接禁用自带的垂直滚动条,从根源上消除残留元素。
  • 自定义滚动条的位置计算改用scroll_view.width - width替代text_input.width,避免因TextInput的布局偏移导致位置错误。
  • 滚动条的policy属性建议用枚举值ScrollBar.AlwaysOn而非字符串,符合Qt QML的规范写法。

修改后的完整代码:

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Window {
  id: window

  width: 640
  height: 480
  visible: true
  title: qsTr("Hello ScrolView and ScrollBar")
  color: "blue"

  ScrollView {
    id: scroll_view
    width: parent.width - 40
    height: parent.height
    // 禁用自带的垂直滚动条
    verticalScrollBarPolicy: Qt.ScrollBarAlwaysOff

    TextInput {
      id: text_input
      anchors.fill: parent
      text: "A very large text but this will be enough to get the picture."
      color: "white"
      readOnly: true
      selectByMouse: true
    }
    ScrollBar.vertical: ScrollBar {
      policy: ScrollBar.AlwaysOn
      parent: scroll_view
      x: scroll_view.width - width
      width: 20
      height: scroll_view.availableHeight
    }
  }
}

补充说明:之前你尝试设置policy为AlwaysOff时只隐藏了自定义滚动条,是因为你把这个属性加在了自定义滚动条上,而非ScrollView本身的滚动条策略上。必须通过ScrollView的verticalScrollBarPolicy来控制自带滚动条的显示状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:23:14