QT 程序启动动画

简述

我们日常用的很多软件都有启动动画,比如Visual Studio和PyCharm在打开软件之前都会有一个加载各种组件的过程。它们的启动动画就是告诉你程序正在打开的过程中,正在加载组件,而不是让你以为程序没有启动。

QT 程序启动动画_第1张图片

QT 程序启动动画_第2张图片

那么,QT中可不可以实现这样的效果呢,当然是可以的。QT提供了QSplashScreen这个类来实现启动动画的效果。 

 


 效果

 


代码之路

最基本的用法:

#include 
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QPixmap lodingPix("heart.png");                         //创建启动需要显示的图片
    QSplashScreen splash(lodingPix);                        //利用图片创建一个QSplashScreen对象
    splash.show();                                          //显示此启动图片
    splash.showMessage("程序正在加载......", Qt::AlignTop|Qt::AlignRight, Qt::red);    //在图片上显示文本信息,第一个参数是文本内容,第二个是显示的位置,第三个是文本颜色
    a.processEvents();                                      //使程序在显示启动画面的同时仍能响应鼠标其他事件

    MainWindow w;
    w.show();
    splash.finish(&w);                                      //在主窗体对象初始化完成后,结束启动画面

    return a.exec();
}

这样我们的启动动画就会出现了,不过停留的时间很短,如果我们想要停留的时间长一些,在停留的时间中我们可以处理加载一些东西的进程可以这样:

#include 
#include 
#include                          //添加QDateTime头文件

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QPixmap lodingPix("heart.png");
    QSplashScreen splash(lodingPix);
    splash.show();
    splash.showMessage("程序正在加载......", Qt::AlignTop|Qt::AlignRight, Qt::red);
    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();
}

或者也可以这样:

#include 
#include 
#include              //需要先在pro文件中添加  CONFIG   += qtestlib

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QPixmap lodingPix("heart.png");
    QSplashScreen splash(lodingPix);
    splash.show();
    splash.showMessage("程序正在加载......", Qt::AlignTop|Qt::AlignRight, Qt::red);
    a.processEvents();
    QTest::qSleep(5000);                                    //qSleep参数为毫秒

    MainWindow w;
    w.show();
    splash.finish(&w);

    return a.exec();
}

 

你可能感兴趣的:(QT,QT,启动动画)