Qt使用QPainter實現(xiàn)自定義圓形進度條
一、項目介紹
本文介紹利用QPainter實現(xiàn)自定義圓形進度條。
二、項目基本配置
新建一個Qt案例,項目名稱為“RoundprogressbarTest”,基類選擇“QWidget”,點擊選中創(chuàng)建UI界面復(fù)選框,完成項目創(chuàng)建。
三、UI界面設(shè)置
UI界面如下:
為簡單起見,這里只設(shè)計兩個控件:
序號 | 名稱 | 類型 | 屬性 |
---|---|---|---|
① | pushButton | QPushButton | text:Start |
② | gridLayout | QGridLayout | / |
四、主程序?qū)崿F(xiàn)
4.1 roundprogressbar.h和roundprogressbar.cpp
由于roundprogressbar.h和roundprogressbar.cpp代碼量較大,這里不進行展示,僅作簡要說明。
函數(shù)如下:
//設(shè)置初始角度,順時針逆時針 void setdefault(int,bool); //設(shè)置外圈寬度 void setOutterBarWidth(float); //設(shè)置內(nèi)圈寬度 void setInnerBarWidth(float); //設(shè)置范圍 void setRange(float, float); //設(shè)置當(dāng)前值 void setValue(float); //設(shè)置外圈顏色 void setOutterColor(const QColor&); //設(shè)置內(nèi)圈漸變色 void setInnerColor(const QColor&,const QColor&); void setInnerColor(const QColor&); //設(shè)置默認文字顏色 void setDefaultTextColor(const QColor&); //設(shè)置控制命令 void setControlFlags(int); //設(shè)置顯示數(shù)字精度 void setPrecision(int);
在構(gòu)造函數(shù)中進行了如下初始化設(shè)定:
//設(shè)置初始角度,順時針逆時針 setdefault(90,true); //設(shè)置默認外圈寬度 setOutterBarWidth(18); //設(shè)置默認內(nèi)圈寬度 setInnerBarWidth(16); //設(shè)置默認范圍 setRange(0,100); //設(shè)置默認值 setValue(75); //設(shè)置外圈顏色 setOutterColor(QColor(233,248,248)); //設(shè)置默認漸變色 setInnerColor(QColor(49, 177, 190),QColor(133, 243, 244)); //設(shè)置默認文字顏色 setDefaultTextColor(QColor(49,177,190)); //設(shè)置默認精度 setPrecision(0); //設(shè)置內(nèi)圈默認文字樣式 setInnerDefaultTextStyle(RoundProgressBar::percent);
設(shè)置初始化角度為90度,順時針,設(shè)置外圈寬度為18,內(nèi)圈寬度為18;設(shè)置默認范圍為0-100,設(shè)置默認值為75,設(shè)置外圈顏色、漸變色、文本顏色和默認精度為0(無小數(shù))設(shè)置內(nèi)圈文字樣式為percent(百分比樣式)。
4.2 widget.h頭文件
頭文件中引入roundprogressbar.h頭文件,按鈕點擊槽函數(shù)和定時器對應(yīng)的槽函數(shù)、timer對象和bar1對象:
private slots: void setText(); void on_pushButton_clicked(); private: RoundProgressBar* bar1; QTimer timer; int i=0;
4.3 widget.cpp源文件
源文件中在構(gòu)造函數(shù)中定義圓形進度條和定時器,將定時器timeout信號和槽函數(shù)setText連接:
//*********************** RoundProgressBar ************************ bar1=new RoundProgressBar(this); bar1->setOutterBarWidth(20); bar1->setInnerBarWidth(20); bar1->setValue(0);//設(shè)置默認值為0 bar1->setControlFlags(RoundProgressBar::all); ui->gridLayout->addWidget(bar1,0,0); //計時 timer.setInterval(100);//設(shè)置計時間隔為0.1s connect(&timer,&QTimer::timeout,this,&Widget::setText);
在析構(gòu)函數(shù)中停止定時器:
Widget::~Widget() { if(timer.isActive()) timer.stop(); delete ui; }
兩個槽函數(shù)定義如下:
//點擊 void Widget::on_pushButton_clicked() { timer.start(); } void Widget::setText() { bar1->setValue(i++); bar1->repaint(); if(i>100) //100停止 { timer.stop(); } }
五、效果演示
完整效果如下:
到此這篇關(guān)于Qt使用QPainter實現(xiàn)自定義圓形進度條的文章就介紹到這了,更多相關(guān)Qt自定義進度條內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ Log日志類輕量級支持格式化輸出變量實現(xiàn)代碼
這篇文章主要介紹了C++ Log日志類輕量級支持格式化輸出變量實現(xiàn)代碼,需要的朋友可以參考下2019-04-04tinyxml 常用的C++ XML解析器非常優(yōu)秀
讀取和設(shè)置xml配置文件是最常用的操作,試用了幾個C++的XML解析器,個人感覺TinyXML是使用起來最舒服的,因為它的API接口和Java的十分類似,面向?qū)ο笮院芎?/div> 2012-11-11最新評論