Qt Quick(QML)中进度条ProgressBar

基本

1
2
3
4
5
6
7
ProgressBar {
id: progressBar
anchors.centerIn: parent
width: 200
height: 20
value: 0.5
}

自定义

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
ProgressBar {
id: progressBar
anchors.centerIn: parent
width: 200
height: 20
value: 0.5

// 自定义进度条背景
background: Rectangle {
implicitWidth: parent.width
implicitHeight: parent.height
radius: 4
color: "#eeeeee" // 背景颜色
}

// 自定义进度条内容
contentItem: Rectangle {
id: progressContent
implicitWidth: parent.width
implicitHeight: parent.height
radius: 4
color: "#4caf50" // 进度条颜色
Component.onCompleted: {
width = progressBar.width * progressBar.value;
}
Binding {
target: progressContent
property: "width"
value: progressBar.width * progressBar.value
}
}
}

上面的Component.onCompletedBinding都不能缺

  • 没有Component.onCompleted初始化有问题
  • 没有Binding后续的更新有问题

模拟更新

1
2
3
4
5
6
7
8
9
10
11
12
13
Timer {
id: timer
interval: 100
running: true
repeat: true
onTriggered: {
if (progressBar.value < 1) {
progressBar.value += 0.01;
} else {
progressBar.value = 0;
}
}
}

组件封装

ZProgressBar.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
35
36
37
38
39
40
41
42
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Item {
property int mRadius: 4
property alias bgColor: progressBackground.color
property alias color: progressContent.color
property alias value: progressBar.value
ProgressBar {
id: progressBar
anchors.centerIn: parent
width: parent.width
height: parent.height
value: 0.0
// 自定义进度条背景
background: Rectangle {
id: progressBackground
implicitWidth: parent.width
implicitHeight: parent.height
radius: mRadius
color: "#eeeeee" // 背景颜色
}

// 自定义进度条内容
contentItem: Rectangle {
id: progressContent
implicitWidth: parent.width
implicitHeight: parent.height
radius: mRadius
color: "#4caf50" // 进度条颜色
Component.onCompleted: {
width = progressBar.width * progressBar.value;
}
Binding {
target: progressContent
property: "width"
value: progressBar.width * progressBar.value
}
}
}
}

调用

1
2
3
4
5
6
7
8
9
10
11
12
import "components" as Components

Components.ZProgressBar {
id: mProgressBar
anchors.centerIn: parent
width: 200
height: 20
value: 0.5
mRadius: 10
color: "#ff0000"
bgColor: "#eeeeee"
}