主要逻辑就是退出当前进程,QProcess::startDetached 开启新的进程
1.简化版
const QString program = QCoreApplication::applicationFilePath();
const QStringList arguments = QCoreApplication::arguments();
const QString directory = QDir::currentPath();
QCoreApplication::exit();
QProcess::startDetached(program, arguments, directory);
2.Qt Creator源码版
class Restarter
{
public:
Restarter(int argc, char *argv[])
{
Q_UNUSED(argc)
m_executable = QString::fromLocal8Bit(argv[0]);
m_workingPath = QDir::currentPath();
}
void setArguments(const QStringList &args) { m_args = args; }
QString executable() const { return m_executable; }
QStringList arguments() const { return m_args; }
QString workingPath() const { return m_workingPath; }
int restartOrExit(int exitCode)
{
return qApp->property("restart").toBool() ? restart(exitCode) : exitCode;
}
int restart(int exitCode)
{
QProcess::startDetached(m_executable, m_args, m_workingPath);
return exitCode;
}
private:
QString m_executable;
QStringList m_args;
QString m_workingPath;
};
int main(int argc, char **argv)
{
Restarter restarter(argc, argv);
QApplication app(argc, argv);
//可以加一些参数传递给重启后应用
restarter.setArguments(app.arguments());
//... ...
//qApp->setProperty("restart",true);
//... ...
return restarter.restartOrExit(app.exec());
}