《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

相关推荐
肥or胖12 小时前
【FFmpeg 快速入门】本地播放器 项目
开发语言·qt·ffmpeg·音视频
小灰灰搞电子18 小时前
Qt Quick 粒子系统详解
开发语言·qt
暴躁茹20 小时前
Qt 将触摸事件转换为鼠标事件(Qt4和Qt5及以上版本)
开发语言·qt·计算机外设
大专生学编程21 小时前
QT简介和QT环境搭建
c++·qt
feiyangqingyun21 小时前
Qt/C++开发监控GB28181系统/视频点播没有ssrc问题的处理/兼容各种设备和应用场景需求
c++·qt·gb28181
小堃学编程1 天前
QT跨平台应用程序开发框架(10)—— Qt窗口
开发语言·qt
轩宇^_^1 天前
Qt CMake 学习文档
数据库·qt·学习
小徐不徐说1 天前
QT技巧之快速搭建串口收发平台
开发语言·c++·qt·串口·软件构建·个人开发·通信
天堂陌客1 天前
QT 交叉编译环境下,嵌入式设备显示字体大小和QT Creator 桌面显示不一致问题解决
开发语言·qt·字库
小堃学编程2 天前
QT跨平台应用程序开发框架(9)—— 容器类控件
开发语言·qt