设置退出码,以指定设置码退出时重新启动程序,代码示例:
testwgt.h
#ifndef TESTWGT_H
#define TESTWGT_H
#include <QApplication>
#include <QWidget>
#include <QPushButton>
const int RETCODE_RESTART = 666;
class TestWgt : public QWidget
{
Q_OBJECT
public:
explicit TestWgt(QWidget *parent = 0);
private:
void initObject();
void initConnect();
signals:
public slots:
void slot_RestartApp();
private:
QPushButton *m_pRestartBtn;
};
#endif // TESTWGT_H
testwgt.cpp
#include "testwgt.h"
#include <QVBoxLayout>
TestWgt::TestWgt(QWidget *parent) : QWidget(parent)
{
initObject();
initConnect();
}
void TestWgt::initObject()
{
this->setFixedSize(300, 200);
m_pRestartBtn = new QPushButton(QString::fromLocal8Bit("重启"));
m_pRestartBtn->setFixedSize(130, 36);
QVBoxLayout *m_MainVLayout = new QVBoxLayout();
m_MainVLayout->addWidget(m_pRestartBtn);
m_MainVLayout->setAlignment(m_pRestartBtn,Qt::AlignCenter);
this->setLayout(m_MainVLayout);
}
void TestWgt::initConnect()
{
connect(m_pRestartBtn, SIGNAL(clicked(bool)),
this, SLOT(slot_RestartApp()));
}
void TestWgt::slot_RestartApp()
{
qApp->exit(RETCODE_RESTART);
}
main.cpp
#include <QProcess>
#include "testwgt.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TestWgt w;
w.show();
int e = a.exec();
if(e == RETCODE_RESTART)
{
// 传入 qApp->applicationFilePath(),启动自己,可以传入启动参数(QStringList插入)
QProcess::startDetached(qApp->applicationFilePath(), QStringList());
return 0;
}
return e;
}