目录
一、实现效果
好啦,废话不多说,直接上实现效果吧
二、实现思路
1. 想要自定义按钮的话,可以继承QPushButton或者继承QWidget,当然也可以是其他窗口类,这个我们直接选择继承QPushButton类,怎么在qtcreator里面新增一个类的操作这里我们就不讲解了,不知道的小伙伴可以去探索一下
2. 继承QPushButton类后,我们需要重写哪些函数呢?
自定义的话,那肯定逃脱不了重写paintEvent函数啦,这个函数可是Qt绘制事件,另外这里也重新实现了mousePressEvent函数,来触发更新操作
3. 想要实现点击旋转,大家肯定有很多想法,比如使用QTimer来增加旋转角度,点击后每次增加一点旋转角度达到看起来旋转一圈的效果,另外还可以使用动画类来实现,当然肯定还有许多实现方法来达到类似的效果,这里的栗子就是使用动画类来实现
哦对了差点忘记怎么找到合适的矢量图标了,我是使用阿里的矢量图标库,链接放在下面啦,免费找到合适的图标哈哈,我感觉比较好用,这里推荐一下。
三、代码实现
当然这里只是粘贴关键代码啦,我相信小伙伴只要关键代码即可实现啦
先放头文件,命名规则的话那就随便你们哈哈
#include <QObject>
#include <QPushButton>
#include <QPixmap>
#include <QVariantAnimation>
class RefreshButton : public QPushButton
{
public:
RefreshButton(QWidget *parent);
void startAnimation();
protected:
void setAngle(double angle);
void paintEvent(QPaintEvent *) override;
void mousePressEvent(QMouseEvent *e) override;
private:
int m_angle = 0;
QPixmap m_pixmap;
QVariantAnimation *m_animation = nullptr;
};
这里是实现的cpp文件
#include <QPainter>
#define ICON_SIZE 100
RefreshButton::RefreshButton(QWidget *parent)
: QPushButton(parent)
{
this->setFixedSize(ICON_SIZE, ICON_SIZE);
m_pixmap = QPixmap(":/ref.svg");
m_pixmap = m_pixmap.scaled(ICON_SIZE, ICON_SIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation);
m_animation = new QVariantAnimation(this);
m_animation->setStartValue(0.0);
m_animation->setEndValue(360.0);
m_animation->setDuration(500);
connect(m_animation, &QVariantAnimation::valueChanged, this, [=](){
update();
this->setAngle(m_animation->currentValue().toDouble());
});
}
void RefreshButton::startAnimation()
{
m_animation->start();
}
void RefreshButton::setAngle(double angle)
{
m_angle = angle;
}
void RefreshButton::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter.save();
//偏移中心点到pixmap中心点
painter.translate(m_pixmap.width() / 2, m_pixmap.height() / 2);
//旋转角度
painter.rotate(m_angle);
//恢复中心点
painter.translate(-m_pixmap.width() / 2, -m_pixmap.height() / 2);
//绘制图片
painter.drawPixmap(0, 0, m_pixmap);
painter.restore();
}
void RefreshButton::mousePressEvent(QMouseEvent *e)
{
Q_UNUSED(e);
m_animation->start();
}
芜湖,如果想要完整的项目的话,那就直接下载前面资源吧,运行环境的话Linux、Windows都试过可以直接编译运行,emmm,好像前面的资源需要VIP,那就直接去我gitee上下载吧