//BOYSLIDER.H
#ifndef BOYSLIDER_H
#define BOYSLIDER_H
#include <QtGui/QtGui>
#include <QtCore/QtCore>
class BOYSlider : public QWidget
{
Q_OBJECT
public:
BOYSlider(QWidget *parent = 0);
~BOYSlider();
virtual void paintEvent ( QPaintEvent * event );
virtual void mousePressEvent ( QMouseEvent * event );
virtual void mouseMoveEvent ( QMouseEvent * event );
void calculateRect();
bool isIn(QPoint point);
private:
enum TYPE{SLIDER = 0,MIDPOINT};
QRect m_rect[2];
QImage *m_slider; //轨道
QImage *m_point; //中间那东西
double m_curPos;
};
#endif // BOYSLIDER_H
//BOYSLIDER.CPP
#include "boyslider.h"
BOYSlider::BOYSlider(QWidget *parent)
: QWidget(parent)
, m_curPos(50)
{
m_slider = new QImage(":/Resources/slider.PNG");
m_point = new QImage(":/Resources/point.png");
setWindowIcon(QIcon(":/Resources/title.png"));
setFixedHeight(60);
}
BOYSlider::~BOYSlider()
{
}
void BOYSlider::paintEvent( QPaintEvent * event )
{
calculateRect(); //计算SLIDER坐标
QPainter painter(this); //绘画
painter.drawImage(m_rect[SLIDER], *m_slider);
painter.drawImage(m_rect[MIDPOINT], *m_point);
}
void BOYSlider::calculateRect()
{
QRect rect = this->rect();
QRect rectTemp;
rectTemp.setX(m_point->width()/2);
rectTemp.setY((rect.height()-m_slider->height())/2);
rectTemp.setRight(rect.right()- m_point->width()/2);
rectTemp.setHeight(m_slider->height());
m_rect[SLIDER] = rectTemp;
double ruleLen = rectTemp.width();
double curPos = ruleLen*m_curPos/100; //POINT在轨道上的位置
rectTemp.setX(rectTemp.x()+curPos-m_point->width()/2); //轨道左边+POINT在轨道上的位置-POINT/2长
rectTemp.setY((rect.height()-m_point->height())/2);
rectTemp.setWidth(m_point->width());
rectTemp.setHeight(m_point->height());
m_rect[MIDPOINT] = rectTemp;
}
void BOYSlider::mouseMoveEvent( QMouseEvent * event )
{
QPoint point = event->pos();
if (isIn(point))
{
m_curPos = (double)(point.x()- m_rect[0].x())/m_rect[0].width()*100;
update();
}
}
void BOYSlider::mousePressEvent( QMouseEvent * event )
{
QPoint point = event->pos();
if (isIn(point))
{
m_curPos = (double)(point.x()- m_rect[0].x())/m_rect[0].width()*100;
update();
}
}
bool BOYSlider::isIn( QPoint point )
{
if (point.x()>=m_rect[0].x() && point.x()<=m_rect[0].right())
{
if (point.y()>=m_rect[0].y() && point.y()<=m_rect[0].bottom())
{
return true;
}
}
return false;
}