C++ 如何重新启动我自己的 qt 应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5129788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:27:49  来源:igfitidea点击:

how to restart my own qt application?

c++qtqt4application-restart

提问by Klaus

i just asking myself how to restart my own qt application?

我只是问自己如何重新启动我自己的 qt 应用程序?

Can somebody please show me an example?

有人可以给我举个例子吗?

回答by masoud

To restart application, try:

要重新启动应用程序,请尝试:

#include <QApplication>
#include <QProcess>

...

// restart:
qApp->quit();
QProcess::startDetached(qApp->arguments()[0], qApp->arguments());

回答by rubenvb

I'm taking the other answers solutions, but better. No need for pointers, but there is a need for a ;after the whilestatement of a do { ... } while( ... );construct.

我正在接受其他答案的解决方案,但更好。不需要指针,但需要;在构造while语句之后do { ... } while( ... );

int main(int argc, char *argv[])
{
    const int RESTART_CODE = 1000;

    do
    {
        QApplication app(argc, argv);
        MainWindow main_window(app);
    } while( app.exec() == RESTART_CODE);

    return return_from_event_loop_code;
}

回答by braggPeaks

Assuming that 1337is your restart code:

假设1337是您的重启代码:

main.cxx

主文件

int main(int argc, char * argv[])
{  
  int result = 0;

  do
  {
     QCoreApplication coreapp(argc, argv);
     MyClass myObj;
     result = coreapp.exec();
  } while( result == 1337 );

  return result;
}

myClass.cxx

myClass.cxx

qApp->exit(1337);

回答by Aise

Doing a real process restart without subclassing:

在没有子类化的情况下重新启动真正的进程:

QCoreApplication a(argc, argv);
int returncode = a.exec();
if (returncode == -1)
{
  QProcess* proc = new QProcess();
  proc->start(QCoreApplication::applicationFilePath());
}
return returncode;

Edit for Mac OS like earlier example.

像前面的示例一样针对 Mac OS 进行编辑。

To restart call

重新开始通话

QCoreApplication::exit(-1);

somewhere in your code.

在您的代码中的某处。

回答by Piotr Dobrogost

Take a look at How to restart an applicationthread on qtcentre.org, where muiseigives this code

在 qtcentre.org 上查看How to restart an applicationthread,muisei给出了这段代码

#define RESTART_CODE 1000
int main(int argc, char *argv[])
{
  int return_from_event_loop_code;
  QPointer<QApplication> app;
  QPointer<MainWindow> main_window;
  do
  {
    if(app) delete app;
    if(main_window) delete main_window;

    app = new QApplication(argc, argv);
    main_window = new MainWindow(app);
    return_from_event_loop_code = app->exec();
  }
  while(return_from_event_loop_code==RESTART_CODE)

  return return_from_event_loop_code;
}

回答by Fivos Vilanakis

I just used the method described above and I noticed that my application crashes on restart. ...then I switched the following lines of code:

我刚刚使用了上面描述的方法,我注意到我的应用程序在重新启动时崩溃了。...然后我切换了以下代码行:

if(app) delete app;
if(main_window) delete main_window;

to:

到:

if(main_window) delete main_window;
if(app) delete app;

and it behaves OK. For some reason the window must be deleted first. Just a note for future readers.

它的行为正常。由于某种原因,必须先删除窗口。只是给未来的读者一个注释。



EDIT:...and a different approach for those who want a real process-restart: You can declare a myApp::Restart() method in your subclass of QApplication. The following version works OK on both MS-Windows & MacOS:

编辑:...对于那些想要真正重新启动进程的人来说,还有一种不同的方法:您可以在 QApplication 的子类中声明一个 myApp::Restart() 方法。以下版本在 MS-Windows 和 MacOS 上都可以正常工作:

// Restart Application
void myApp::Restart(bool Abort)
{
    // Spawn a new instance of myApplication:
    QProcess proc;
#ifdef Q_OS_WIN
    proc.start(this->applicationFilePath());
#endif    

#ifdef Q_OS_MAC
    // In Mac OS the full path of aplication binary is:
    //    <base-path>/myApp.app/Contents/MacOS/myApp
    QStringList args;
    args << (this->applicationDirPath() + "/../../../myApp.app");
    proc.start("open", args);
#endif

    // Terminate current instance:
    if (Abort) // Abort Application process (exit immediattely)
        ::exit(0);
    else
        this->exit(0); // Exit gracefully by terminating the myApp instance
}

回答by Eike

This slight variation on Rubenvb's idea works with PyQt. clearSettingsis the method that triggers the restart.

Rubenvb 想法的这种轻微变化适用于 PyQt。clearSettings是触发重启的方法。

class GuiMain

    #Most of implementation missing

    def clearSettings(self):
        #Clearing the settings missing
        QApplication.exit(GuiMain.restart_code)

    restart_code = 1000

    @staticmethod
    def application_main():
        """
        The application's main function. 
        Create application and main window and run them.
        """
        while True:
            app = QApplication(sys.argv)
            window = GuiMain()
            window.show()
            ret = app.exec_()
            if ret != GuiMain.restart_code:
                break
            del window
            del app

回答by Angie Quijano

Here is the code:

这是代码:

main.cpp:

主.cpp:

int main(int argc, char *argv[])
{
    int currentExitCode = 0;

    do {
     QApplication a(argc, argv);
     MainWindow w;
     w.show();
     currentExitCode = a.exec();
    } while( currentExitCode == MainWindow::EXIT_CODE_REBOOT );

    return currentExitCode;

}

mainwindow.h

主窗口.h

    class MainWindow : public QMainWindow
    {
        Q_OBJECT

    public:
        explicit MainWindow(QWidget *parent = 0);
        static int const EXIT_CODE_REBOOT;//THIS IS THE IMPORTANT THING TO ADD TO YOUR CODE
        ~MainWindow();
    private slots:
        void slotReboot();//AND THIS ALSO

    //ALL THE OTHER VARIABLES
    }

The slotReboot()is the slot that will receive the signal of the QActionI'm going to show in the mainwindow.cpp

slotReboot()是将接收QAction我将在 mainwindow.cpp 中显示的信号的插槽

mainwindow.cpp

主窗口.cpp

First initialize EXIT_CODE_REBOOT:

首先初始化EXIT_CODE_REBOOT

int const MainWindow::EXIT_CODE_REBOOT = -123456789;

and declare a QActionpointer:

并声明一个QAction指针:

QAction* actionReboot;

then in the MainWindowconstructor:

然后在MainWindow构造函数中:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

     actionReboot = new QAction( this );
     actionReboot->setText( tr("Restart") );
     actionReboot->setStatusTip( tr("Restarts the application") );
     connect( actionReboot, SIGNAL (triggered()),this, SLOT (slotReboot()));
}

And finally you need to send the signal (in the part of your code you need), in this way:

最后,您需要以这种方式发送信号(在您需要的代码部分):

actionReboot->trigger();

I did the code I showed following these instructions: How to make an application restartable - Qt Wiki

我按照以下说明执行了我显示的代码:How to make an application restartable - Qt Wiki