1. 首先建立新的工程,选择Qt Widgets Application
2. 在界面中插入一个QPushButton
3. 工程中添加新文件,选择C++ Class
4. 为新添加的类命名,提前准备好的图片red.jpg和blue.jpg也加入工程资源文件
5. pushbuttonprogressbar.h
#ifndef PUSHBUTTONPROGRESSBAR_H
#define PUSHBUTTONPROGRESSBAR_H
#include<QPushButton>
#include<QPainter>
#include<QPaintEvent>
#include<QImage>
#include<QRectF>
class PushButtonProgressBar:public QPushButton
{
Q_OBJECT
public:
PushButtonProgressBar(QWidget* parent=Q_NULLPTR);
~PushButtonProgressBar();
bool setPercent(int iPercent);
void paintEvent(QPaintEvent* event);
private:
double m_Percent;
};
#endif // PUSHBUTTONPROGRESSBAR_H
6. pushbuttonprogressbar.cpp
setPercent为自己编写的函数,关键在于调用update()触发paintEvent事件,在paintEvent事件中对按钮的背景进行绘制
#include "pushbuttonprogressbar.h"
PushButtonProgressBar::PushButtonProgressBar(QWidget *parent):QPushButton(parent),m_Percent(0)
{
}
PushButtonProgressBar::~PushButtonProgressBar()
{
}
bool PushButtonProgressBar::setPercent(int iPercent)
{
if(iPercent<0||iPercent>100)
return false;
m_Percent=iPercent/100.0;
update();//调用次函数,触发paintEvent
return true;
}
void PushButtonProgressBar::paintEvent(QPaintEvent* event)
{
int ButtonWidth,ButtonHeight;
QPainter painter(this);
QImage image;
QRectF target,source;
ButtonWidth=this->width();
ButtonHeight=this->height();
//已完成部分的显示
image=QImage(":blue.jpg");//设置显示图片路径
target=QRectF(0.0,0.0,m_Percent*ButtonWidth,ButtonHeight);
source=QRectF(0.0,0.0,m_Percent*image.width(),image.height());
painter.drawImage(target,image,source);
//未完成部分的显示
image=QImage(":red.jpg");//设置显示图片路径
target=QRectF(m_Percent*ButtonWidth,0.0,(1-m_Percent)*ButtonWidth,ButtonHeight);
source=QRectF(m_Percent*image.width(),0.0,(1-m_Percent)*image.width(),image.height());
painter.drawImage(target,image,source);
//显示按钮上的文字
painter.setFont(QFont("Times New Roman",20));
painter.drawText(rect(),Qt::AlignCenter,this->text());
}
7. 将qpushbutton提升为pushbuttonprogressbar
8. 在按钮点击槽函数写入小小测试功能,每单击一次进度增加10%
void MainWindow::on_pushButton_clicked()
{
static int iClicked=0;
iClicked++;
ui->pushButton->setPercent(iClicked*10%110);
}
9. 最后编译运行效果
单击0次、1次、5次、10次的效果
关键点:
在paintEvent中使用QPainter重绘按钮背景,将两张图按比例画出