重啟應用程序是一種常見的操作,在Qt中實現非常簡單,需要用到QProcess類一個靜態方法:
1 // program, 要啟動的程序名稱 2 // arguments, 啟動參數 3 bool startDetached(const QString &program, const QStringList &arguments);
下面通過一個示例來演示:
【創建一個窗口】

接下來實現點擊【Restart】按鈕實現程序重啟的功能。
1 // dialog.h 2 #ifndef DIALOG_H 3 #define DIALOG_H 4 5 #include <QDialog> 6 7 // define a retcode: 773 = 'r'+'e'+'s'+'t'+'a'+'r'+'t' = restart 8 static const int RETCODE_RESTART = 773; 9 10 namespace Ui { 11 class Dialog; 12 } 13 14 class Dialog : public QDialog 15 { 16 Q_OBJECT 17 18 public: 19 explicit Dialog(QWidget *parent = 0); 20 ~Dialog(); 21 22 private slots: 23 void on_pushButton_clicked(); 24 25 private: 26 Ui::Dialog *ui; 27 }; 28 29 #endif // DIALOG_H
1 // dialog.cpp 2 #include "dialog.h" 3 #include "ui_dialog.h" 4 5 Dialog::Dialog(QWidget *parent) : 6 QDialog(parent), 7 ui(new Ui::Dialog) 8 { 9 ui->setupUi(this); 10 ui->pushButton->setStyleSheet("color:black"); 11 } 12 13 Dialog::~Dialog() 14 { 15 delete ui; 16 } 17 18 void Dialog::on_pushButton_clicked() 19 { 20 qApp->exit(RETCODE_RESTART); 21 }
在main函數中判斷退出碼是否為“RETCODE_RESTART”,來決定是否重啟。
1 // main.cpp 2 #include "dialog.h" 3 #include <QApplication> 4 #include <QProcess> 5 6 int main(int argc, char *argv[]) 7 { 8 QApplication a(argc, argv); 9 Dialog w; 10 w.show(); 11 12 //return a.exec(); 13 int e = a.exec(); 14 if(e == RETCODE_RESTART) 15 { 16 // 傳入 qApp->applicationFilePath(),啟動自己 17 QProcess::startDetached(qApp->applicationFilePath(), QStringList()); 18 return 0; 19 } 20 return e; 21 }
【舉一反三】
按照這個思路,也可以實現Qt應用程序的自升級。不過一般自升級至少需要兩個exe,避免文件占用問題。
例如: app.exe 和 update.exe,app如需升級,可以在退出時啟動update.exe;update.exe 下載並更新應用程序后,啟動app.exe。
