首先看下效果图:
核心部分代码如下:
psshowslider.h
class psshowslider : public QFrame { Q_OBJECT public: explicit psshowslider(QWidget *parent = 0); ~psshowslider(); //设置最大值 void setMaxValue(double maxvalue); //得到最大值 double getMaxValue(); //设置最小值 void setMinValue(double minvalue); //得到最小值 double getMinValue(); //设置值 void setValue(double value); //取得值 double getValue(); protected: void paintEvent(QPaintEvent *); private: Ui::psshowslider *ui; //滑动条最大值 double maxvalue; //滑动条最小值 double minvalue; //设置显示的值 double value; };
psshowslider.cpp里面主要是paintEvent()函数的重写.
void psshowslider::paintEvent(QPaintEvent *) { QPainter painter(this); //移动坐标系 painter.translate(20, height() / 2); QPen pen(Qt::white, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); painter.setPen(pen); painter.drawLine(0, 40, 0, -40); //画上边直线 painter.drawLine(0, -30, 320, -30); //画下边直线 painter.drawLine(0, 30, 320, 30); //画上下直线刻度以及文字 int num = 1; int x, y; QPen pen2(Qt::white, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); QPoint point; painter.setPen(pen2); for (; num < 21; num++) { x = 15 * num; if (num % 2 == 0) { y = -20; point.setX(x - 8); point.setY(y + 10); painter.drawText(point, QString::number(50 * num)); } else { y = -25; } painter.drawLine(x, -30, x, y); } //设置线性渐变 QLinearGradient linearGradient = QLinearGradient(0, 0, 300, 0); linearGradient.setColorAt(0.0, Qt::cyan); linearGradient.setColorAt(0.6, Qt::yellow); linearGradient.setColorAt(1, Qt::red); //设置画刷 QBrush qsh(linearGradient); painter.setBrush(qsh); painter.setPen(Qt::cyan); //画矩形 painter.drawRect(0, -5, this->getValue() / this->getMaxValue() * 300, 34); }
每次当类属性value改变之后,只需要调用类的update()方法或者repaint()方法即可.
文章的脚注信息由WordPress的wp-posturl插件自动生成