Qt窗口动画实战:Qt实现呼吸灯效果
在嵌入式设备或桌面应用中,呼吸灯效果是一种常见且优雅的UI动画,常用于指示系统状态或吸引用户注意。本文将介绍如何使用Qt动画框架实现平滑的呼吸灯效果。
一、实现原理
利用Qt自带的动画框架来实现,具体实现看代码:
2、代码实现
#ifndef BUTTON_H
#define BUTTON_H
#include <QPropertyAnimation>
#include <QSequentialAnimationGroup>
#include <QPainter>
#include <QColor>
#include <QWidget>
class BreathingLight : public QWidget {
Q_OBJECT
Q_PROPERTY(int alpha READ alpha WRITE setAlpha)
public:
BreathingLight(QWidget *parent = nullptr) : QWidget(parent), m_alpha(0) {
setFixedSize(200, 200);
// 创建两个动画,一个从0到255,一个从255到0
QPropertyAnimation *animationUp = new QPropertyAnimation(this, "alpha");
animationUp->setDuration(2500); // 动画时长为2000毫秒
animationUp->setStartValue(20); // 起始透明度
animationUp->setEndValue(255); // 结束透明度
animationUp->setEasingCurve(
QEasingCurve::InOutQuad); // 使用平滑的缓入缓出动画曲线
QPropertyAnimation *animationDown = new QPropertyAnimation(this, "alpha");
animationDown->setDuration(2500); // 动画时长为2000毫秒
animationDown->setStartValue(255); // 起始透明度
animationDown->setEndValue(20); // 结束透明度
animationDown->setEasingCurve(
QEasingCurve::InOutQuad); // 使用平滑的缓入缓出动画曲线
// 创建一个动画组,将两个动画添加进去,并设置为循环播放
QSequentialAnimationGroup *animationGroup =
new QSequentialAnimationGroup(this);
animationGroup->addAnimation(animationUp);
animationGroup->addAnimation(animationDown);
animationGroup->setLoopCount(-1); // 无限循环
animationGroup->start(); // 启动动画组
}
int alpha() const { return m_alpha; }
void setAlpha(int alpha) {
m_alpha = alpha;
update(); // 更新窗口,触发重绘事件
}
protected:
void paintEvent(QPaintEvent *event) override {
Q_UNUSED(event);
QPainter painter(this);
QColor color(0, 255, 0, m_alpha); // 绿色,使用 m_alpha 透明度
painter.setBrush(color);
painter.setPen(Qt::NoPen);
QRect paint_rect = rect();
paint_rect.adjust(90, 90, -90, -90);
painter.drawEllipse(paint_rect); // 绘制一个椭圆,填充整个窗口
}
private:
int m_alpha;
};
#include <QApplication>
#include <QTableView>
#include <QHeaderView>
#include <QStandardItemModel>
#include "button.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//button.show();
BreathingLight light;
light.show();
return a.exec();
}
#endif // BUTTON_H
3、总结:
利用Qt自带的动画系统可以很方便的就做出炫酷的效果,相比较其他传统的UI,Qt这个方案对用户来说其实还是很方便的。