Qt5.9利用QSplashScreen实现程序启动动画

如何在程序加载完成之前让用户觉得你的程序不是卡死,从而提高用户体验呢?

加载图片并延时(main.cpp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <QApplication>
#include <QPixmap>
#include <QSplashScreen>
#include <QDateTime>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QPixmap pixmap(":/images/hh"); //加载资源文件中的图片
QSplashScreen splash(pixmap); //利用图片创建一个QSplashScreen对象
splash.show(); //显示图片
QDateTime time = QDateTime::currentDateTime();
QDateTime currentTime = QDateTime::currentDateTime(); //记录当前时间
while (time.secsTo(currentTime) <= 5) //5为需要延时的秒数
{
currentTime = QDateTime::currentDateTime();
a.processEvents();
}
Dialoghome w;
w.show();
splash.finish(&w);
return a.exec();
}

开机加载GIF动图并延时(main.cpp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <QApplication>
#include <QMovie>
#include <QPixmap>
#include <QLabel>
#include <QSplashScreen>
#include <QDateTime> //添加QDateTime头文件

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QPixmap pixmap(":/images/bg"); //在动画的底层会显示这张图片
// 这里很重要,用透明色填充,这样就相当于加了一个透明背景而不是有色彩的背景
pixmap.fill(Qt::transparent); //
QSplashScreen splash(pixmap); //利用图片创建一个QSplashScreen对象
QMovie movie(":/images/hh"); //创建启动需要显示的图片
QLabel label(&splash);
label.setMovie(&movie);
movie.start(); //启动GIF
splash.show(); //显示图片
QDateTime time = QDateTime::currentDateTime();
QDateTime currentTime = QDateTime::currentDateTime(); //记录当前时间
while (time.secsTo(currentTime) <= 5) //5为需要延时的秒数
{
currentTime = QDateTime::currentDateTime();
a.processEvents(); //使程序在显示启动画面的同时仍能响应鼠标其他事件
};
MainWindow w;
w.show();
splash.finish(&w); //在主窗体对象初始化完成后,结束启动画面
return a.exec();
}

参考文章
[1]Qt中通过Qpixmap设置图片透明度
[2]Qt QSplashScreen 开机加载图片和动图