#include <QSplashScreen> #include <QMouseEvent> class AppSplashScreen : public QSplashScreen { Q_OBJECT public: explicit AppSplashScreen(QPixmap pixmap); ~AppSplashScreen(); void mousePressEvent(QMouseEvent *event); }; AppSplashScreen::AppSplashScreen(QPixmap pixmap) : QSplashScreen(pixmap) { this->setAttribute(Qt::WA_TransparentForMouseEvents, false); this->setWindowFlags(Qt::FramelessWindowHint); this->setAttribute(Qt::WA_TranslucentBackground); } /* 重写mousePressEvent */ void AppSplashScreen::mousePressEvent(QMouseEvent *event) { return; } AppSplashScreen::~AppSplashScreen() { }
this->setAttribute(Qt::WA_TransparentForMouseEvents, false); 设置禁止鼠标事件到父窗口 this->setWindowFlags(Qt::FramelessWindowHint); 设置窗口无边框 this->setAttribute(Qt::WA_TranslucentBackground); 设置窗口透明
/** * @brief 在应用启动过程中附上gif作为开启动画 */ void MainWindow::InitSplash(void) { int width,height; setFixedSize(800, 460); splash = new AppSplashScreen(QPixmap(":/png/png/splash.gif").scaled(width, height)); label = new QLabel(splash); mv = new QMovie(":/png/png/splash.gif"); bool istablet = QGSettings("org.ukui.SettingsDaemon.plugins.tablet-mode").get("tablet-mode").toBool(); if(istablet == true){ width = QGuiApplication::primaryScreen()->geometry().width(); height = QGuiApplication::primaryScreen()->geometry().height(); }else{ width = this->width(); height = this->height(); } splash->setFixedSize(width,height); label->setFixedSize(QSize(width , height)); mv->setScaledSize(label->size()); QScreen *screen = QGuiApplication::primaryScreen(); splash->move((screen->geometry().width() - width) / 2,(screen->geometry().height() - height) / 2); splash->showMessage(QObject::tr("正在启动程序..."), Qt::AlignRight | Qt::AlignTop, Qt::white); label->setMovie(mv); mv->start(); if(istablet == true){ splash->showFullScreen(); }else{ splash->show(); } for(int i=0; i<100; i++) { qApp->processEvents(); QThread::msleep(1); } }
QScreen *screen = QGuiApplication::primaryScreen(); splash->move((screen->geometry().width() - width) / 2,(screen->geometry().height() - height) / 2);
label->setMovie(mv); mv->start();
/** * @brief 销毁new出来的 QMovie QLabel AppSplashScreen */ void MainWindow::DestorySplash(void) { splash->finish(this); delete mv; mv = NULL; delete label; label = NULL; delete splash; splash = NULL; }
/** * @brief 不断设置动画消息 */ void MainWindow::SplashShowmsg(const QString msg) { label->setMovie(mv); mv->start(); Qt::Alignment topRight = Qt::AlignRight | Qt::AlignTop; splash->showMessage(msg,topRight, Qt::white); for(int i=0;i<10;i++) { qApp->processEvents(); splash->repaint(); } }
MainWindow::MainWindow(QStringList str,QWidget *parent) :QWidget(parent) { mainWid = new QWidget(); InitSplash(); /* 主界面做其他事情 */ mainWid->show(); DestorySplash(); }
上面描述了如何设置一个QSplashScreen,从而让你的程序开启时出现动画效果。但对于效率来说,它为了绘制动画做了很多不必要的sleep和repaint/show。