《Qt窗口动画实战:窗口渐隐渐现效果》

《Qt窗口动画实战:窗口渐隐渐现效果》

在桌面应用开发中,优雅的窗口动画能显著提升用户体验。本文将分享我如何使用Qt实现窗口的渐隐渐现效果,以及在此过程中解决的各种技术难题。

1、看看效果如何

2、设计过程

1、设计思路
  1. 窗口显示时:从完全透明渐变到完全不透明
  2. 窗口隐藏时:从完全不透明渐变到完全透明
  3. 支持自定义动画时长
  4. 兼容Windows、macOS、Linux三大平台
2、设计方案

经过调研,我选择了以下技术方案:

核心机制:QPropertyAnimation

3、实现的具体过程

mainwindow.h文件的实现

cpp 复制代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPropertyAnimation>
#include <QPushButton>

class MainWindow : public QMainWindow
{
    Q_OBJECT
    Q_PROPERTY(qreal windowOpacity READ windowOpacity WRITE setWindowOpacity)

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void fadeOut();
    void fadeIn();

private:
    QPropertyAnimation *animation;
    QPushButton *fadeOutBtn;
    QPushButton *fadeInBtn;
};

#endif // MAINWINDOW_H 

mainwindow.cpp文件的实现

cpp 复制代码
#include "mainwindow.h"
#include <QVBoxLayout>
#include <QWidget>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle("test fade window");
    resize(400, 300);

    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(centralWidget);
    setCentralWidget(centralWidget);

    fadeOutBtn = new QPushButton("fade out", this);
    fadeInBtn = new QPushButton("fade in", this);
    
    layout->addWidget(fadeOutBtn);
    layout->addWidget(fadeInBtn);

    animation = new QPropertyAnimation(this, "windowOpacity", this);
    animation->setDuration(1000); 


    connect(fadeOutBtn, &QPushButton::clicked, this, &MainWindow::fadeOut);
    connect(fadeInBtn, &QPushButton::clicked, this, &MainWindow::fadeIn);
}

MainWindow::~MainWindow()
{
}

void MainWindow::fadeOut()
{
    animation->setStartValue(1.0);
    animation->setEndValue(0.0);
    animation->start();
}

void MainWindow::fadeIn()
{
    animation->setStartValue(0.0);
    animation->setEndValue(1.0);
    animation->start();
} 

main.cpp实现:

cpp 复制代码
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
} 

源码地址:https://github.com/MingYueRuYa/QtDemo

相关推荐
Fleshy数模5 分钟前
PyQt5 登录界面开发全流程:从环境配置到可视化设计
开发语言·python·qt
用户805533698032 小时前
现代Qt开发教程(新手篇)1.6——内存管理
c++·qt
m0_502724953 小时前
qt键盘钩子完善
stm32·qt·计算机外设
广州灵眸科技有限公司3 小时前
瑞芯微(EASY EAI)RV1126B QT GUI例程方案
linux·服务器·开发语言·网络·人工智能·qt·物联网
xcjbqd04 小时前
Qt Quick中QML与C++交互详解及场景切换实现
c++·qt·交互
Drone_xjw14 小时前
一次 Qt 程序在 Kylin 系统下表头“白屏”的排查之旅
qt·kylin·一次
GISer_Jing20 小时前
前端图片、动图与动画全解析(含PNG/APNG/Lottie/GIF/Canvas/WebGL/WebGPU)
前端·3d·动画·webgl
尘中远1 天前
Qwt 7.0 新特性介绍 — 更现代、更强大的Qt数据可视化库
qt·qwt·科学绘图·曲线图
会飞的胖达喵1 天前
基于qt开发的RedisDesk
开发语言·qt
油炸自行车1 天前
【Qt】运行 `windeployqt.exe` 打包Qt发布包,遇到警告的解决方法 (Warning: Cannot find any.....)
开发语言·qt·vs·打包·windeployqt·软件部署