如下图所示:
介绍
通过qss实现,只需要一个多彩背景图,通过QImage获取颜色,然后来设置进度条,便可以实现动态多彩进度条(根据图片设定颜色)
其中,上面3个进度条就是通过以下3个图片实现的:
如果想实现其它颜色,只需要改图片即可
代码如下
ProgressBar.h:
1 #ifndef PROGRESSBAR_H
2 #define PROGRESSBAR_H
3 #include <QtGui>
4
5 class ProgressBar : public QWidget
6 {
7 Q_OBJECT
8
9 QProgressBar m_bar;
10 QLabel m_value;
11 QSlider m_slider;
12 QImage m_image;
13
14 protected slots:
15 void onvalueChanged(int value);
16 public:
17 explicit ProgressBar(const QString& fileName,QWidget *parent = 0);
18 };
19
20 #endif // PROGRESSBAR_H
ProgressBar.cpp:
1 #include "ProgressBar.h"
2
3 ProgressBar:: ProgressBar(const QString& fileName,QWidget *parent ) :
4 QWidget(parent),
5 m_bar(this),
6 m_value(this),
7 m_slider(this),
8 m_image(fileName)
9 {
10
11 m_bar.setMaximum(100);
12 m_bar.setMinimum(0);
13 m_bar.setValue(0);
14 m_bar.setTextVisible(false);
15 m_bar.setFixedHeight(20);
16
17 m_slider.setMaximum(100);
18 m_slider.setMinimum(0);
19 m_slider.setValue(0);
20 m_slider.setOrientation(Qt::Horizontal);
21
22 m_value.setText(QString("%1%").arg(m_bar.value()));
23 m_value.setAlignment(Qt::AlignRight|Qt::AlignVCenter);
24 m_value.setMinimumWidth(40);
25 /*设置布局*/
26 QHBoxLayout* hlayout = new QHBoxLayout();
27 hlayout->addWidget(&m_slider);
28 hlayout->addWidget(&m_value,0,Qt::AlignRight);
29
30 QVBoxLayout* vlayout = new QVBoxLayout();
31
32 vlayout->addWidget(&m_bar);
33 vlayout->addLayout(hlayout);
34 setLayout(vlayout);
35
36 connect(&m_slider,SIGNAL(valueChanged ( int)),&m_bar,SLOT(setValue (int)));
37 connect(&m_bar,SIGNAL(valueChanged ( int)),this,SLOT(onvalueChanged (int)));
38
39 onvalueChanged(m_bar.value());
40 }
41 void ProgressBar::onvalueChanged(int value)
42 {
43 QString qss= "QProgressBar{"
44 "border: 1px solid rgb(16, 135, 209);"
45 "background: rgba(248,248,255,180);"
46 "border-radius: 6px; }"
47 "QProgressBar::chunk:enabled {"
48 "border-radius: 4px; "
49 "background: qlineargradient(x1:0, y1:0, x2:1, y2:0" ;
50
51 double v = m_bar.maximum();
52 double EndColor=static_cast<double>(value)/v ; //获取比例
53
54 for(int i=0;i<100;i++)
55 {
56 double Current = EndColor*i/100;
57 QRgb rgb = m_image.pixel((m_image.width()-1)*Current,m_image.height()/2);
58 QColor c(rgb);
59 qss.append(QString(",stop:%1 rgb(%2,%3,%4)").arg(i/100.0).arg(c.red()).arg(c.green()).arg(c.blue()));
60 }
61
62 qss.append(");}");
63 m_bar.setStyleSheet(qss);
64 m_value.setText(QString("%1%").arg(m_bar.value()));
65 }