Making an application restartable/rebootable

If you have the need to make an application restartable depending on the user interaction you have to follow this steps:

Create an exit code that represents your reboot/restart event

It is a good idea to define this code as a static variable in your main window:

  1. static int const EXIT_CODE_REBOOT;

and initialize it with a value:

  1. int const MainWindow::EXIT_CODE_REBOOT = -123456789;

Otherwise you can define a global variable or a constant value.

Define a slot in your application main window that will perform the exit from the application

Define a slot that will exits the application using the reboot code:

  1. void MainWindow::slotReboot()
  2. {
  3.     qDebug() << "Performing application reboot..";
  4.     qApp->exit( MainWindow::EXIT_CODE_REBOOT );
  5. }

Create an action to handle the reboot

Create an action that will consume the above slot in order to exit with the reboot code. Something like the following will work:

  1.    actionReboot = new QAction( this );
  2.     actionReboot->setText( tr("Restart") );
  3.     actionReboot->setStatusTip( tr("Restarts the application") );
  4.     connect( actionReboot,
  5.              SIGNAL(triggered()),
  6.              this,
  7.              SLOT(slotReboot()) );

Modify the application cycle

The last step consists in modifying the application main function to handle the new cycle that will allow reboot:

  1. int main(int argc, char *argv[])
  2. {
  3.     int currentExitCode = 0;
  4.  
  5.     do{
  6.         QApplication a(argc, argv);
  7.         MainWindow w;
  8.         w.show();
  9.         currentExitCode = a.exec();
  10.  
  11.     }while( currentExitCode == MainWindow::EXIT_CODE_REBOOT );
  12.  
  13.     return currentExitCode;
  14.  
  15.  
  16. }

Categories: