QT develops an example of the welcome interface for the application

  • 2020-05-27 06:41:13
  • OfStack

The main interface is too slow to start, usually more than 10 seconds, so you want to add a welcome screen, wait for the program to load before displaying the main interface.

The main interface (class name MainWindow) starts slowly because the constructor needs to do a lot of initialization.

The Welcome class was created as a welcome interface, starting with the idea of creating an object of the Welcome class in the main function, then show(), for the main interface, calling its show() method when the constructor is about to return, and calling close() of welcome. However, the welcome screen always shows only the border, no content is displayed, and the background of the form is also virtual.

Reason analysis:

In QT, form various events distribution is performed by QApplication in main function, the last one line of code is called object QApplication exec () method, this method performs, the application of events can be distributed processing, but in main function, create instances of MainWindow, always waiting for MainWindow constructor is done, will perform to the object QApplication exec () method, so before this welcome screen event is not the response, The paintEvent() function will not be executed, so it will not be displayed properly. When the constructor of MainWindow is completed and the QApplication object can handle event distribution, the welcome screen will not be displayed, but the main screen will be displayed directly.

You can only find a way to get the MainWindow constructor to return immediately, leaving the initialization for later processing. But who calls the working code for initialization? The constructor of the welcome class can't call it either, or it would be slow to display. My solution is to use QTimer timing for a short period of time to automatically trigger the execution of the initialization code, so that it doesn't take up the constructor's execution time and QApplication can be up and running as soon as possible.

The following is the abbreviated code:

main.cpp


int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  //... Other code 
  WelcomeWindow *welcome=new WelcomeWindow();
  MainWindow w(welcome);
 
  return app.exec();
}

The constructor for MainWindow


this->welcome=welcome;
if(welcome != 0){
  welcome->show();
  timerInit=new QTimer();
  timerInit->setInterval(100);
  timerInit->setSingleShot(true);// Set up the Timer Only the trigger 1 time 
  timerInit->start();
  connect(timerInit, SIGNAL(timeout()), SLOT(init()));
}else{
  init();
}

MainWindow's init() function (puts the initialization code of the original constructor into init())


if(welcome!=0){
  welcome->close();
  delete welcome;
  this->show();
}

Related articles: