兼容Qt4/Qt5版本Qml控件ScrollBar

1. ScrollBar演示

ScrollBar

2. 对外属性

  • 继承于Rectangle;
  • target属性继承于Flickable(默认值父控件);
  • orientation设置控件水平还是垂直方向(默认值垂直方向).

ScrollBar.qml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import QtQuick 2.0

Rectangle {
id: root

property Flickable target: parent // parent: Flickable
property int orientation: Qt.Vertical
/*
orientation : enumeration
This property holds the orientation of the scroll bar.
Possible values:
|Constant |Description|
|Qt.Horizontal|Horizontal|
|Qt.Vertical |Vertical(default)|
*/

width: orientation == Qt.Vertical ? 15 : target.width
height: orientation == Qt.Vertical ? target.height : 15
color: "white"
opacity: 0.3
radius: 5

Rectangle {
y: orientation == Qt.Vertical ? target.visibleArea.yPosition * target.height : 0
x: orientation == Qt.Vertical ? 0 : target.visibleArea.xPosition * target.width
width: orientation == Qt.Vertical ? parent.width :
target.visibleArea.widthRatio * target.width
height: orientation == Qt.Vertical ? target.visibleArea.heightRatio * target.height :
parent.height
color: "black"
radius: root.radius
opacity: 0.7
}
}

3. 使用示例

3.1 图片显示器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import QtQuick 2.0
import "../"

Rectangle {
anchors.fill: parent

Flickable {
id: view
anchors.fill: parent
contentWidth: picture.width
contentHeight: picture.height

Image {
id: picture
source: "Test.png"
asynchronous: true
}
}

ScrollBar {
target: view
}

ScrollBar {
target: view
orientation: Qt.Horizontal
}
}

3.2 ListView附加滚动条

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import QtQuick 2.0
import "../"

ListView {
anchors.fill: parent

model: 10
delegate: Rectangle {
width: parent.width; height: 100
color: "lightblue"
Text {
anchors.centerIn: parent
text: index
}
}

ScrollBar { }
}

4. 注意事项

  • 在Qt4下使用需要将QtQuick 2.x改为QtQuick 1.x

5. 源码地址

1
https://github.com/QtComponent/ScrollBar.git