Qt编写自定义控件:简单的方式绘制渐变进度条

代码:

#ifndef MYPROGRESSBAR_H
#define MYPROGRESSBAR_H

#include <QProgressBar>

class myProgressBar : public QProgressBar
{
public:
    myProgressBar(QWidget * parent = nullptr);

protected:
    void paintEvent(QPaintEvent *event)override;
};

#endif // MYPROGRESSBAR_H
#include "myprogressbar.h"
#include <QPainter>
#include <QStyleOptionProgressBar>
#include <QStylePainter>
#include <QDebug>
#include <QPaintEvent>

myProgressBar::myProgressBar(QWidget *parent)
    :QProgressBar(parent)
{
    setMinimumSize(180,150);
    setAlignment(Qt::AlignCenter);
}

void myProgressBar::paintEvent(QPaintEvent *event)
{
    QStylePainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing,true);
    QStyleOptionProgressBar option;

    initStyleOption(&option);
//    painter.drawControl(QStyle::CE_ProgressBar,option);
    QStyleOptionProgressBar opt1 = option;
    opt1.rect = this->style()->subElementRect(QStyle::SE_ProgressBarContents, &opt1, this);

    QStyleOptionProgressBar opt2 = option;

    QRect rect = QRect(opt1.rect.topLeft().x(),
                       opt1.rect.topLeft().y(),
                       opt1.rect.width() * opt1.progress / opt1.maximum,
                       opt1.rect.height());

    auto eventRect = event->rect();
    QLinearGradient linearGradient(eventRect.topLeft(),eventRect.topRight());
    linearGradient.setColorAt(0.0,Qt::red);
    linearGradient.setColorAt(0.3,Qt::cyan);
    linearGradient.setColorAt(0.7,Qt::green);
    linearGradient.setColorAt(1.0,Qt::blue);

    painter.fillRect(rect,linearGradient);

    if (option.textVisible)
    {
        opt2.rect = this->style()->subElementRect(QStyle::SE_ProgressBarLabel, &opt2, this);
        painter.setPen(Qt::red);
        painter.drawControl(QStyle::CE_ProgressBarLabel, opt2);
    }
}

使用:

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout * vb = new QVBoxLayout(this);
    myProgressBar * bar = new myProgressBar(this);
    QSlider * slider = new QSlider(Qt::Horizontal,this);
    slider->setRange(0,100);
    bar->setRange(0,100);
    vb->setContentsMargins(20,20,20,20);
    vb->addWidget(bar);
    vb->addStretch();
    vb->addWidget(slider);
    connect(slider,&QSlider::valueChanged,bar,&QProgressBar::setValue);
}

效果:

相关博文:QT风格(QStyle):绘制一个自定义QProgressBar_友善啊,朋友的博客-CSDN博客