Qt工作笔记-QML自定义圆形进度条(C++后端处理数据)
生活随笔
收集整理的這篇文章主要介紹了
Qt工作笔记-QML自定义圆形进度条(C++后端处理数据)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
原理
源碼
?
原理
1.使用QML中的Canvas繪制圓形,用一種顏色,說明是未讀取,再用另外一種顏色覆蓋到原來的顏色!說明進度!
2.使用setContextProperty把C++中的某個繼承了QObject的類映射到QML中!
3.QML中有一個計時器,去實時讀取QObject中的進度!
?
程序運行截圖如下:
?
源碼
程序結構如下:
源碼如下:
mycicular.h
#ifndef MYCICULAR_H #define MYCICULAR_H#include <QObject>QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACEclass MyCicular : public QObject {Q_OBJECT public:MyCicular(QObject *parent = 0);~MyCicular();Q_INVOKABLE int getCurrentValue();Q_INVOKABLE void finished();protected slots:void addValueTimeout();private:int m_endValue;int m_startValue;QTimer *m_timer; };#endif // MYCICULAR_Hmain.cpp
#include <QApplication> #include <QQuickView> #include <QQmlApplicationEngine> #include <QQmlContext> #include "mycicular.h"int main(int argc, char *argv[]) {QApplication a(argc, argv);MyCicular myCicular;QQuickView view;view.engine()->rootContext()->setContextProperty("canvas", &myCicular);view.setResizeMode(QQuickView::SizeViewToRootObject);view.setSource(QUrl("qrc:/main.qml"));view.show();return a.exec(); }mycicular.cpp
#include "mycicular.h" #include <QTimer> #include <QDebug> #include <QMessageBox>MyCicular::MyCicular(QObject *parent) : QObject(parent) {m_startValue = 0;m_endValue = 1000;m_timer = new QTimer;connect(m_timer, SIGNAL(timeout()), this, SLOT(addValueTimeout()));m_timer->start(5); }MyCicular::~MyCicular() {delete m_timer; }int MyCicular::getCurrentValue() {return ((double)m_startValue / (double)m_endValue) * 360; }void MyCicular::finished() {QMessageBox::information(NULL, "提示", "程序讀取結束"); }void MyCicular::addValueTimeout() {m_startValue++;if(m_startValue >= m_endValue){m_timer->stop();} }CircularProgress.qml
import QtQuick 2.4Canvas{property int radius: 100property real progress: 0property real arcWidth: 2id:canvaswidth: 2 * radius + arcWidthheight: 2 * radius + arcWidthText{anchors.centerIn: parentfont.pointSize: 15text: Math.floor((parent.progress / 360) * 100) + "%"}onPaint:{var ctx = getContext("2d")ctx.beginPath()ctx.strokeStyle = "#AAAAAA"ctx.lineWidth = 2ctx.arc(width / 2, height / 2, radius, 0, Math.PI * 2, false)ctx.stroke()var r = progress * Math.PI / 180ctx.beginPath()ctx.strokeStyle = "#148014"ctx.lineWidth = 2ctx.arc(width / 2, height / 2, radius, 0 - 90 * Math.PI / 180, r - 90 * Math.PI / 180, false)ctx.stroke()} }main.qml
import QtQuick 2.7 import QtQuick.Controls 2.0Item {visible: truewidth: 400height: 300CircularProgress{id: circularProgressanchors.centerIn: parent}Timer{id: timerrunning: truerepeat: trueinterval: 100onTriggered: {console.log(circularProgress.progress)if(circularProgress.progress == 360){timer.running = falsecanvas.finished()}circularProgress.progress = canvas.getCurrentValue()circularProgress.requestPaint()}} }?
總結
以上是生活随笔為你收集整理的Qt工作笔记-QML自定义圆形进度条(C++后端处理数据)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ STL string的构造函数
- 下一篇: C++ opengl 绘制三角形带