文章目录
前言效果核心代码mybutton.hmybutton.cppwidget.hwidget.cpp前言
Qt通过重新封装QPushButton类,实现自定义(异形)按钮,并且实现鼠标点击后的上下跳动特效,
具体效果如下图所示,将QPushButton默认的方形按钮换为“AVIC”异形图标按钮,鼠标点击后先向下跳动20像素,然后再向上跳动20像素。
效果
核心代码
右键工程文件夹Add New,选择新建一个C++ Class,定义Class Name为MyButton,需要Add Q_OBJECT可自动生成mybutton.h及mybutton.cpp。
将MyButton的父类修改为QPushButton,并且重新定义构造函数为
MyButton(QString normalImg, QString pressImg = “”);
第一个参数为正常状态下的图标的地址,第二个参数为按下状态下的图标地址,默认为空
mybutton.h
#ifndef MYBUTTON_H#define MYBUTTON_H#include <QObject>#include <QWidget>#include <QPushButton>#include <QDebug>#include <QPropertyAnimation>class MyButton : public QPushButton{Q_OBJECTpublic:explicit MyButton(QString normalImg, QString pressImg = "");//按钮初始状态下的图片地址QString normalImgPath;//按钮按下状态下的图片地址QString pressedImgPath;signals:public slots://按钮向下移动20像素void zoom1();//按钮向上移动20像素void zoom2();};#endif // MYBUTTON_H
mybutton.cpp
#include "mybutton.h"MyButton::MyButton(QString normalImg, QString pressImg){normalImgPath = normalImg;pressedImgPath = pressImg;QPixmap pixmap;bool ret = pixmap.load(normalImgPath);if(!ret){qDebug() << normalImg <<"load image failure!";}this->setFixedSize(pixmap.width(),pixmap.height());this->setStyleSheet("QPushButton{border:0px}");this->setIcon(pixmap);this->setIconSize(QSize(pixmap.width(),pixmap.height()));}void MyButton::zoom1(){//创建动画对象QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry");//设置时间间隔animation->setDuration(200);//创建开始位置animation->setStartValue(QRect(this->x(),this->y(),this->width(),this->height()));//创建结束位置animation->setEndValue(QRect(this->x(),this->y()+30,this->width(),this->height()));//设置缓和曲线,QEasingCurve::OutBounce为弹跳结果animation->setEasingCurve(QEasingCurve::OutBounce);//开始执行动画animation->start();}void MyButton::zoom2(){QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry");animation->setDuration(200);animation->setStartValue(QRect(this->x(),this->y()+30,this->width(),this->height()));animation->setEndValue(QRect(this->x(),this->y(),this->width(),this->height()));animation->setEasingCurve(QEasingCurve::OutBounce);animation->start();}
widget.h
#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include "mybutton.h"QT_BEGIN_NAMESPACEnamespace Ui {class Widget; }QT_END_NAMESPACEclass Widget : public QWidget{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private:Ui::Widget *ui;MyButton *startBtn;};#endif // WIDGET_H
widget.cpp
startBtn = new MyButton(“:/3.png”);
在Widget构造函数里新创建一个MyButton类,传入按钮初始状态下的图片地址,本案例下按钮没有按下状态
connect(startBtn,&MyButton::clicked,={ startBtn->zoom1(); startBtn->zoom2();
将按钮的点击信号与实现按钮的向下20像素、向上20像素响应动作进行绑定
#include "widget.h"#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget){ui->setupUi(this);startBtn = new MyButton(":/3.png");startBtn->setParent(this);startBtn->move(this->width()*0.5-startBtn->width()*0.5,this->height()*0.6);connect(startBtn,&MyButton::clicked,[=](){startBtn->zoom1();startBtn->zoom2();});}Widget::~Widget(){delete ui;}