zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    firefox, chrome常见插件
    数据库左连接left join、右连接right join、内连接inner join on 及 where条件查询的区别
    Springmvc + mybatis + spring 配置,spring事物
    Android如何连接MySQL数据库
    Android MP3录音实现
    Android RecyclerView的基本使用
    Java输入流之BufferReader和Scanner的用法!
    Android 网络通信框架Volley简介
    your project contains error(s),please fix them before running your application.错误总结
    新建android项目报错,代码中找不到错误
  • 原文地址:https://www.cnblogs.com/pyw0818/p/8048046.html
Copyright © 2011-2022 走看看