QML製作環形進度條,使用ConicalGradient錐形漸變

QML中沒有直接提供環形進度條組件,但是我們可以自己實現,如用Canvas、Shape、QPainter等等。我參照濤哥的代碼(https://github.com/jaredtao/TaoQuick),使用QtGraphicalEffects模塊的ConicalGradient實現了一個自己的環形進度條(https://github.com/gongjianbo/QmlComponentStyle)。

主要實現思路:通過 ConicalGradient 錐形漸變來區分進度條的兩種顏色,然後使用 Rectangle 的 border 來作爲 mask 截取出圓環部分。

實現效果和代碼:

//CircleProgress
import QtQuick 2.12
import QtGraphicalEffects 1.0

ConicalGradient {
    id: control
    width: 200
    height: 200

    property int barWidth: 20
    property color foregroundColor: Qt.rgba(0,0.5,0,1)
    property color backgroundColor: Qt.rgba(0.7,0.7,0.7,1)
    property color textColor: Qt.rgba(0,0.5,0,1)
    property double minValue: 0
    property double maxValue: 100
    property double value: 0
    property double __progress: value/(maxValue-minValue)

    smooth: true
    antialiasing: true
    source: Rectangle {
        width: control.width
        height: control.height
        color: "transparent"
        border.color: control.backgroundColor
        border.width: control.barWidth
        radius: width / 2
    }

    gradient: Gradient {
        GradientStop { position: 0.0; color: control.foregroundColor }
        GradientStop { position: control.__progress; color: control.foregroundColor }
        GradientStop { position: control.__progress + 0.00001; color: control.backgroundColor }
        GradientStop { position: 1.0; color: control.backgroundColor }
    }

    //具體的設置可以再單獨引出來
    Text{
        anchors.centerIn: parent
        text: (control.__progress*100).toFixed(2)+" %"
        font.pixelSize: 20
        color: control.textColor
    }
}
//main.qml
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("GongJianBo 1992")

    CircleProgress{
        id: circle_progress
        anchors.centerIn: parent
        value: 50

        //測試用,循環設置進度值
        NumberAnimation on value {
            from: 0
            to: 100
            duration: 5000
            running: true
            loops: Animation.Infinite
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章