Qt应用程序重启

重启应用程序是一种常见的操作,在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。

 

posted @ 2017-12-16 23:15  Day_Dreamer  阅读(6869)  评论(0编辑  收藏  举报