有些應用程式啟動較慢,這時通常會先顯示一個啟動畫面,讓等待的感覺沒那麼漫長。Qt 要做到這件事很簡單,只要使用 QSplashScreen 類:在主視窗顯示之前先顯示一張圖片,還能在圖片上疊印文字,提示使用者目前的初始化進度。
一般來說,啟動畫面的程式碼都寫在 main() 裡,放在呼叫 QApplication::exec() 之前。具體實現如下:
//main.cpp
#include <QtGui/QApplication>
#include <QTextCodec>
#include <QSplashScreen>
#include <QDesktopWidget>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
//在程式中能使用中文必須進行字體編碼處理
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
QApplication a(argc, argv);
QSplashScreen *splash = new QSplashScreen;
splash->setPixmap(QPixmap("F:\\Windows QT\\Notepad\\start.jpg"));
splash->show();
//讓主視窗延遲一段時間顯示
for(int i = 0; i < 200; i++)
{
splash->repaint();
}
MainWindow w;
w.show();
//將視窗移動到螢幕中央
w.move((QApplication::desktop()->width() - w.width())/2,
(QApplication::desktop()->height() - w.height())/2);
splash->finish(&w);
delete splash;
return a.exec();
}
啟動畫面:
主程式運行畫面:
實務上那個空轉迴圈只是延時的權宜寫法,正式專案建議用 splash->showMessage() 在真正的初始化階段逐步更新提示文字,再呼叫 finish() 淡出。