惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
美团技术团队
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
有赞技术团队
有赞技术团队
GbyAI
GbyAI
宝玉的分享
宝玉的分享
腾讯CDC
M
MIT News - Artificial intelligence
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
月光博客
月光博客
MyScale Blog
MyScale Blog
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog

博客园 - Day_Dreamer

在Qt中使用Font Awesome图标 Github上的一些高分Qt开源项目【多图】 Qt中容器类应该如何存储对象 Qt 编程指南 如何选择合适的Qt5版本? Qt绘图 如何让QT程序以管理员权限运行(UAC) Qt类继承关系图 回归Qt——写在Qt5.10发布之日 inno setup判断是Windows系统版本 Inno Setup自定义卸载文件名称【收藏】 Inno Setup静默安装msi【收藏】 - Day_Dreamer - 博客园 Inno Setup使用教程【收藏】 - Day_Dreamer - 博客园 Inno Setup目录常量【收藏】 Inno setup常用代码补充【收藏】 Inno setup常用代码【收藏】 详细解说STL string 【收藏】 QT for Window程序部署 Qt程序的国际化支持【收藏】
Qt应用程序重启
Day_Dreamer · 2017-12-16 · via 博客园 - Day_Dreamer

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