此示例演示了一个自定义滚动条的方法。
自定义滚动条:
import QtQuick 2.0
Item
{
id: scrollBar
property real position//范围是 0.0 - 1.0
property real pageSize//范围是 0.0 - 1.0
property int orientation : Qt.Vertical
//浅色半透明背景
Rectangle
{
id: background
anchors.fill: parent
radius: orientation === Qt.Vertical ? (width/2 - 1) : (height/2 - 1)
color: "white"
opacity: 0.3
}
//滑块
Rectangle
{
x: orientation === Qt.Vertical ? 1 : (scrollBar.position * (scrollBar.width-2) + 1)
y: orientation === Qt.Vertical ? (scrollBar.position * (scrollBar.height-2) + 1) : 1
width: orientation === Qt.Vertical ? (parent.width-2) : (scrollBar.pageSize * (scrollBar.width-2))
height: orientation === Qt.Vertical ? (scrollBar.pageSize * (scrollBar.height-2)) : (parent.height-2)
radius: orientation === Qt.Vertical ? (width/2 - 1) : (height/2 - 1)
color: "black"
opacity: 0.7
}
}
简单的代码,定义一个半透明的背景和在其上方的滑块。
主界面:
import QtQuick 2.0
Rectangle {
width: 640
height: 480
Flickable {
id: view
anchors.fill: parent
contentWidth: picture.width
contentHeight: picture.height
Image
{
id: picture
source: "pics/niagara_falls.jpg"
asynchronous: true
}
//仅在 view 移动时显示滚动条
//movingVertically、movingHorizontally当用户拖动或轻弹视图时,视图当前是否在垂直、水平方向移动。
states: State
{
name: "ShowBars"
when: view.movingVertically || view.movingHorizontally
PropertyChanges
{
verticalScrollBar.opacity: 1
horizontalScrollBar.opacity: 1
}
}
transitions: Transition
{
NumberAnimation { properties: "opacity"; duration: 400 }
}
}
//垂直滚动条
ScrollBar
{
id: verticalScrollBar
width: 12; height: view.height-12
anchors.right: view.right
opacity: 0
orientation: Qt.Vertical
position: view.visibleArea.yPosition
pageSize: view.visibleArea.heightRatio
}
//水平滚动条
ScrollBar
{
id: horizontalScrollBar
width: view.width-12; height: 12
anchors.bottom: view.bottom
opacity: 0
orientation: Qt.Horizontal
position: view.visibleArea.xPosition
pageSize: view.visibleArea.widthRatio
}
}
主窗口放置一个 Flickable,水平滚动条放在下面,垂直滚动条放在左边。
默认滚动条都是隐藏的,当拖动 Flickable 的视图时,滚动条显示出来。显示的过程使用动画效果。
滚动条的自定义属性position、pageSize绑定 Flickable 可见区域组的相关属性从而确定滚动条应该处于的位置。
这里没有使用鼠标操作的类型,即滚动条不参与交互只是用来显示视图当前位置。