#include "switchbutton.h"
#include <QTimer>
#include <QPainter>
#include <QDebug>
#include <QPaintEvent>
#include <QBitmap>
#include <QPixmap>
SwitchButton::SwitchButton(QWidget *parent) :
QPushButton(parent),state(false),_pos(0),isReady(true)
{
closeTimer = new QTimer(this);
connect(closeTimer,SIGNAL(timeout()),this,SLOT(closeAnimation()));
openTimer = new QTimer(this);
connect(openTimer,SIGNAL(timeout()),this,SLOT(openAnimation()));
onPixmap = new QPixmap(":/image/on-slide1.png");
offPixmap = new QPixmap(":/image/off-slide1.png");
on_offPixmap = new QPixmap(":/image/on-off-slide1.png");
resize(onPixmap->size());
this->shortcut();
}
bool SwitchButton::getState()
{
return state;
}
void SwitchButton::setState(bool _state)
{
state = _state;
emit stateChange(state);
if(state)
{
if(_pos < 0)
_pos = 0;
openTimer->start(10);
closeTimer->stop();
}
else
{
openTimer->stop();
closeTimer->start(10);
}
isReady = false;
}
void SwitchButton::setStateWithoutAnimation(bool _state)
{
state = _state;
emit stateChange(state);
if(state)
{
//_pos = buttonSize.width() - on_offPixmap->width();
_pos = 97 - on_offPixmap->width();
}
else
{
_pos = 0;
}
update();
}
void SwitchButton::mousePressEvent(QMouseEvent *e)
{
changeState();
QPushButton::mousePressEvent(e);
}
void SwitchButton::paintEvent(QPaintEvent *e)
{
buttonSize = this->size();
QPainter painter(this);
//painter.drawPixmap(0,0,100,100,QPixmap("://ui/11.png"));
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::NoPen);
int _width = buttonSize.width();
int _height = buttonSize.height();
if(_pos < 0)
{
if(state)
_pos = 97 - on_offPixmap->width();
else
_pos = 0;
}
double _scale = double(_pos+3) / double(_width);
painter.drawPixmap(0,0,_width,_height,*offPixmap);
painter.drawPixmap(QRect(0,0,_pos+3,_height),onPixmap->copy(0,0,_scale * onPixmap->width(),onPixmap->height()));
painter.drawPixmap(_pos,0,_height * 56.0/30.0,_height,*on_offPixmap);
}
void SwitchButton::setButtonSize(int w, int h)
{
buttonSize.setWidth(w);
buttonSize.setHeight(h);
buttonSize = this->size();
update();
}
void SwitchButton::changeState()
{
if(state == true)
{
// openTimer->stop();
// closeTimer->start(10);
// state = 0;
setState(false);
}
else
{
// openTimer->start(10);
// closeTimer->stop();
// state = 1;
setState(true);
}
isReady = false;
}
void SwitchButton::closeAnimation()
{
_pos -= 3;
if(_pos <= 0)
{
_pos = 0;
closeTimer->stop();
isReady = true;
repaint();
return;
}
update();
}
void SwitchButton::openAnimation()
{
_pos += 3;
if(_pos < 0)
_pos = 0;
if(_pos >= buttonSize.width() - on_offPixmap->width())
{
_pos = buttonSize.width() - on_offPixmap->width();
openTimer->stop();
isReady = true;
repaint();
return;
}
update();
}