写在前面
此篇开始是对旅行模拟系统中遇到的问题的总结记录,以及相关知识点的记录,以备后续查看。
按钮封装是比较基础的内容,此部分学习自bilibili用户“寒风落轻尘”上载的视频——黑马2018年qt视频,是我认为B站qt基础教学非常好的视频,老师幽默风趣且教学安排较好。
下面开始内容:
要实现的功能
qt自带的按钮是比较一般,尤其在win10我认为按钮做的反而越来越丑,因此实现按钮的封装对于美化一个软件的ui界面是非常有必要的,并且要有按钮点击的特效,如实现点击后按钮向下跳跃后返回原位等。
流程
//mypushbutton.h
#ifndef MYPUSHBUTTON_H
#define MYPUSHBUTTON_H
#include <QPushButton>
class MyPushButton : public QPushButton
{
Q_OBJECT
public:
MyPushButton(QString normalImg, QString pressImg = "");
QString normalImgPath;
QString pressedImgPath;
//向下跳跃
void zoom1();
//向上跳跃
void zoom2();
signals:
public slots:
};
#endif // MYPUSHBUTTON_H
//mypushbutton.cpp
#include "mypushbutton.h"
#include <QDebug>
#include <QPropertyAnimation>
//封装一个自己的按钮,该按钮能实现点击图片弹出对话框
//传入两个参数,第一个是正常的图片,第二个是按下后显示的图片
//因为需求的按钮只需要实现动画效果即可,不需要第二张图片,仅传入一个参数即可
MyPushButton::MyPushButton(QString normalImg, QString pressImg)
{
//保存正常图片路径和 选中后显示的路径
this->normalImgPath = normalImg;
this->pressedImgPath = pressImg;
QPixmap pix;
bool ret = pix.load(this->normalImgPath);
if(!ret)
{
//此行代码实现几个Qstring之间 的拼接
QString str = QString("1%图片加载失败").arg(this->normalImgPath);
qDebug()<<str;
return;
}
//设定大小为正常的0.5倍
this->setFixedSize(pix.width()*0.5,pix.height()*0.5);
//设置图片
this->setIcon(pix);
//设置图片大小为正常的0.5倍
this->setIconSize(QSize(pix.width()*0.5,pix.height()*0.5));
}
//向下跳跃
void MyPushButton::zoom1()
{
QPropertyAnimation *animation = new QPropertyAnimation(this,"geometry");
//设定时间间隔
animation->setDuration(100);
//设置动画对象起始位置
animation->setStartValue(QRect(this->x(),this->y(),this->width(),this->height() ));
//设置动画对象结束位置
animation->setEndValue(QRect(this->x(),this->y()+8 ,this->width(),this->height() ));
//设置曲线
animation->setEasingCurve(QEasingCurve::Linear);
//执行动画
animation->start();
}
//向上跳跃
void MyPushButton::zoom2()
{
QPropertyAnimation *animation = new QPropertyAnimation(this,"geometry");
//设定时间间隔
animation->setDuration(100);
//设置动画对象起始位置
animation->setStartValue(QRect(this->x(),this->y()+8,this->width(),this->height() ));
//设置动画对象结束位置
animation->setEndValue(QRect(this->x(),this->y(),this->width(),this->height() ));
//设置曲线
animation->setEasingCurve(QEasingCurve::Linear);
//执行动画
animation->start();
}
如何使用
在使用该封装的按钮时,如下所示:
//成都按钮创建
MyPushButton *Chengdu = new MyPushButton(":/city/Chengdu.png");
Chengdu->setParent(this); Chengdu->move(100,280);
connect(Chengdu,&QPushButton::clicked,[=](){
//点击按钮,实现弹起特效
Chengdu->zoom1(); Chengdu->zoom2();
//点击按钮,弹出该城市时刻表
city_clicked = 0; //0代表成都
tree = new ScheduelTree;//创建出新的窗口,显示时刻表信息
tree->FromA(city_clicked);//调用该函数将点击的城市city_clicked值赋给tree中的city,将Map1中的***head给tree中的quote,并在此设置窗口标题
//************注意此处*************
//如何传递一个指针数组的头指针?将widget中的tmp1赋给FromA,FromA中以schedule ***tmp接收,并令那个类中声明的schedule ***quote接收tmp,才可以使用
tree->VehicalTime(); //调用该函数显示窗口中的各种信息(时刻表等)
tree->exec(); //显示该窗口(模态)
});
END