效果:
代码:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
protected:
void paintEvent(QPaintEvent *event)override;
void mousePressEvent(QMouseEvent *event)override;
void mouseReleaseEvent(QMouseEvent* event)override;
private:
bool isOn{false};
QTimer timer;
int x;
void onTimer();
bool runing{false};
};
#endif // WIDGET_H
#include "widget.h"
#include <QPainter>
#include <QMouseEvent>
#include <math.h>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
connect(&timer,&QTimer::timeout,this,&Widget::onTimer);
timer.setInterval(40);
QTimer::singleShot(100,[this]
{
QRect rect = this->rect();
QRect outRoundRect = rect.adjusted(3,3,-3,-3);
x = outRoundRect.x() + 2;
this->update();
});
}
Widget::~Widget()
{
}
void Widget::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
isOn = !isOn;
timer.start();
}
return QWidget::mousePressEvent(event);
}
void Widget::mouseReleaseEvent(QMouseEvent* event)
{
return QWidget::mouseReleaseEvent(event);
}
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.save();
painter.setRenderHint(QPainter::Antialiasing,true);
painter.setRenderHint(QPainter::SmoothPixmapTransform,true);
painter.setRenderHint(QPainter::TextAntialiasing,true);
painter.setPen(Qt::transparent);
QRect rect = this->rect();
QRect outRoundRect = rect.adjusted(3,3,-3,-3);
if(x > outRoundRect.x() + outRoundRect.width() * 0.45 - 2)
{
x = outRoundRect.x() + outRoundRect.width() * 0.45 - 2;
if(runing)
{
timer.stop();
runing = false;
}
}
if(x < outRoundRect.x() + 2)
{
x = outRoundRect.x() + 2;
if(runing)
{
timer.stop();
runing = false;
}
}
if(isOn)
{
if(runing)
painter.setBrush(QColor("#E7E7E7"));
else
painter.setBrush(QColor("#D93152"));
painter.drawRoundRect(outRoundRect,6,6);
painter.setBrush(Qt::white);
QRect innerRect;
if(runing)
innerRect = QRect(x,outRoundRect.y() + 2,outRoundRect.width() * 0.55,outRoundRect.height() - 4);
else
innerRect = QRect(outRoundRect.x() + outRoundRect.width() * 0.45 - 2 ,outRoundRect.y() + 2,outRoundRect.width() * 0.55,outRoundRect.height() - 4);
painter.drawRoundRect(innerRect,8,8);
}
else
{
if(runing)
painter.setBrush(QColor("#D93152"));
else
painter.setBrush(QColor("#E7E7E7"));
painter.drawRoundRect(outRoundRect,6,6);
painter.setBrush(Qt::white);
QRect innerRect;
if(runing)
innerRect = QRect(x,outRoundRect.y() + 2,outRoundRect.width() * 0.55,outRoundRect.height() - 4);
else
innerRect = QRect(outRoundRect.x() + 2,outRoundRect.y() + 2,outRoundRect.width() * 0.55,outRoundRect.height() - 4);
painter.drawRoundRect(innerRect,8,8);
}
painter.restore();
}
void Widget::onTimer()
{
runing = true;
QRect rect = this->rect();
if(isOn)
x += rect.width() * 0.072;
else
x -= rect.width() * 0.072;
update();
}