首先看下效果图:

Qt QPainter动态进度条[根据值大小改变进度]_QPainter


部分核心代码如下:

类声明:


1. class psshowslider : public QFrame  
2. {
3. Q_OBJECT
4.
5. public:
6. explicit psshowslider(QWidget *parent = 0);
7. ~psshowslider();
8. //设置最大值
9. void setMaxValue(double maxvalue);
10. //得到最大值
11. double getMaxValue();
12.
13. //设置最小值
14. void setMinValue(double minvalue);
15. //得到最小值
16. double getMinValue();
17.
18. //设置值
19. void setValue(double value);
20. //取得值
21. double getValue();
22.
23. protected:
24. void paintEvent(QPaintEvent *);
25.
26. private:
27. Ui::psshowslider *ui;
28. //滑动条最大值
29. double maxvalue;
30. //滑动条最小值
31. double minvalue;
32. //设置显示的值
33. double value;
34.
35. };



类方法里面主要是paintEvent方法的实现.

1. void psshowslider::paintEvent(QPaintEvent *) {  
2. this);
3. //移动坐标系
4. painter.translate(20, height() / 2);
5. QPen pen(Qt::white, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
6. painter.setPen(pen);
7. painter.drawLine(0, 40, 0, -40);
8.
9. //画上边直线
10. painter.drawLine(0, -30, 320, -30);
11. //画下边直线
12. painter.drawLine(0, 30, 320, 30);
13. //画上下直线刻度以及文字
14. int num = 1;
15. int x, y;
16. QPen pen2(Qt::white, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
17. QPoint point;
18. painter.setPen(pen2);
19. for (; num < 21; num++) {
20. x = 15 * num;
21. if (num % 2 == 0) {
22. y = -20;
23. point.setX(x - 8);
24. point.setY(y + 10);
25. painter.drawText(point, QString::number(50 * num));
26. else {
27. y = -25;
28. }
29. painter.drawLine(x, -30, x, y);
30. }
31.
32. //设置线性渐变
33. QLinearGradient linearGradient = QLinearGradient(0, 0, 300, 0);
34. linearGradient.setColorAt(0.0, Qt::cyan);
35. linearGradient.setColorAt(0.6, Qt::yellow);
36. linearGradient.setColorAt(1, Qt::red);
37. //设置画刷
38. QBrush qsh(linearGradient);
39. painter.setBrush(qsh);
40.
41. painter.setPen(Qt::cyan);
42. //画矩形
43. this->getValue() / this->getMaxValue() * 300, 34);
44.
45. }

每次文本框的值变化之后,调用psshowslider的update或者repaint方法即可.