最开始学习qml的时候,想实现一个条纹进度条,当时还不熟悉动画,做不出来,只做了个静止的。qml学习和使用了快1年之际,把这个遗憾弥补下。
先上效果图,颜色取自Bootflat。
以下是源码,先上StripeProgressBar.qml
import QtQuick 2.7
import QtQuick.Controls 2.1ProgressBar {id: controlimplicitWidth: Math.max(background ? background.implicitWidth : 0,contentItem.implicitWidth + leftPadding + rightPadding)implicitHeight: Math.max(background ? background.implicitHeight : 0,contentItem.implicitHeight + topPadding + bottomPadding)property bool stripe: falseproperty color backgroundColor: "#E6E9ED"property color stripeColor: "#5EBDE1"property color progressColor: "#3BAFDA"background: Rectangle {implicitWidth: 200implicitHeight: 20x: control.leftPaddingy: control.topPadding + (control.availableHeight - height) / 2width: control.availableWidthcolor: control.backgroundColorradius: 3}contentItem: Item{implicitWidth: 200implicitHeight: 20Rectangle {width: control.visualPosition * parent.widthheight: parent.heightcolor: control.progressColorclip:trueradius: 3Canvas{id:canvasvisible: control.stripewidth: parent.width*2height: parent.heightcontextType: "2d"function rounding(value,base){return Math.ceil(value/base)*base}SequentialAnimation {loops: Animation.Infiniterunning: canvas.visibleNumberAnimation {target: canvasproperty: "x"from: 0to: -canvas.height*2duration: 1900}ScriptAction {script: canvas.x = 0}}onPaint: {context.fillStyle=control.stripeColorcontext.lineWidth=0var startPostion=0var stripeWidth=parent.heightvar coupleStripeWidth=stripeWidth*2var stopPosion=rounding(parent.width+coupleStripeWidth,coupleStripeWidth)for(var loop=startPostion;loop<stopPosion;loop+=coupleStripeWidth){context.beginPath();context.moveTo(loop,0)context.lineTo(loop+stripeWidth,0)context.lineTo(loop+coupleStripeWidth,stripeWidth)context.lineTo(loop+stripeWidth,stripeWidth)context.lineTo(loop,0)context.closePath();context.fill()}}}}}
}
再上main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0ApplicationWindow {visible: truewidth: 640height: 480title: qsTr("Hello World")Flow{anchors.fill: parentanchors.leftMargin: 100anchors.topMargin: 50spacing: 30StripeProgressBar{width: 400value: 0.3}StripeProgressBar{width: 400value: 0.3stripe: true}StripeProgressBar{width: 400value: 0.35stripe: trueprogressColor: "#8CC152"stripeColor: "#9DCA6B"}StripeProgressBar{width: 400value: 0.4stripe: trueprogressColor: "#3CBC9B"stripeColor: "#54C6A9"}StripeProgressBar{width: 400value: 0.5stripe: trueprogressColor: "#F6BB42"stripeColor: "#F7C55E"}StripeProgressBar{width: 400value: 0.55stripe: trueprogressColor: "#DA4453"stripeColor: "#DF5F6C"}StripeProgressBar{width: 400value: 0.6stripe: trueprogressColor: "#4A89DC"stripeColor: "#5D9CEC"}StripeProgressBar{width: 400value: 1.0stripe: trueprogressColor: "#967ADC"stripeColor: "#AC92EC"}}
}