自定义简单SLIDER

//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;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值