由于QSlider鼠标点一下是固定移动一定的位置。我想要的效果是鼠标点哪里,滑块就跳到哪里。所以继承QWidget自己实现了一个这样的Slider,都是用QPainter绘制出来的,对应的取值是自己算的,大小写死了,只实现了水平方向的。这里稍作记录。
先看下效果,这里录制动图没有把鼠标录进去:
下面直接贴代码:
.h文件:
#ifndef SLIDERWIDGET_H
#define SLIDERWIDGET_H
#include <QWidget>
#include <QMouseEvent>
class SliderWidget : public QWidget
{
Q_OBJECT
public:
explicit SliderWidget(int w, int h, QWidget *parent = 0);
void setMaxVal(qreal val);
void setMinVal(qreal val);
void setVal(qreal val);
qreal getCurVal() const;
qreal getMinVal() const;
qreal getMaxVal() const;
protected:
void paintEvent(QPaintEvent *e);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
private:
void getCurPoint(QMouseEvent *event);
signals:
void sigPositonChange(qreal curVal);
private:
QPoint m_curPoint;
qreal m_maxVal;
qreal m_minVal;
qreal m_curVal;
};
#endif // SLIDERWIDGET_H
.cpp文件:
#include "sliderwidget.h"
#include <QPainter>
SliderWidget::SliderWidget(int w, int h, QWidget *parent):
QWidget(parent), m_maxVal(100), m_minVal(0)
{
this->setFixedSize(w, h);
m_curPoint = QPoint(11, 0);
}
void SliderWidget::setMaxVal(qreal val)
{
m_maxVal = val;
}
void SliderWidget::setMinVal(qreal val)
{
m_minVal = val;
}
void SliderWidget::setVal(qreal val)
{
m_curVal = val;
int posX = (this->width() - 22)*(m_curVal - m_minVal)/(m_maxVal - m_minVal) + 11;
m_curPoint = QPoint(posX, 0);
update();
}
qreal SliderWidget::getCurVal() const
{
return m_curVal;
}
qreal SliderWidget::getMinVal() const
{
return m_minVal;
}
qreal SliderWidget::getMaxVal() const
{
return m_maxVal;
}
void SliderWidget::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.setBrush(QColor(39,105,188));
painter.setPen(Qt::NoPen);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawRoundedRect(QRect(0, this->height()/5*2, m_curPoint.x(),
this->height()/5), 4, 4);
painter.setBrush(QColor(206, 206, 206));
painter.drawRoundedRect(QRect(m_curPoint.x(), this->height()/5*2, this->width() - m_curPoint.x(),
this->height()/5), 4, 4);
QPen pen;
pen.setWidth(2);
pen.setColor(QColor(206, 206, 206));
painter.setBrush(Qt::white);
painter.setPen(pen);
painter.drawEllipse(QPointF(m_curPoint.x(), this->height()/2), 10, 10);
}
void SliderWidget::mousePressEvent(QMouseEvent *event)
{
getCurPoint(event);
}
void SliderWidget::mouseMoveEvent(QMouseEvent *event)
{
getCurPoint(event);
}
void SliderWidget::getCurPoint(QMouseEvent *event)
{
if(event->pos().x() < 11)
{
m_curPoint = QPoint(11, 0);
}
else if(event->pos().x() > this->width() - 11)
{
m_curPoint = QPoint(this->width() - 11, 0);
}
else
{
m_curPoint = event->pos();
}
update();
m_curVal = (qreal)(m_curPoint.x() - 11)/(this->width() - 22)*(m_maxVal - m_minVal) + m_minVal;
emit sigPositonChange(m_curVal);
}