qt 自動重啟(兩種方法)

來源:互聯網
上載者:User

標籤:視窗   訊號   自動重啟   win   string   quit   exec   方案   準備   

所謂自動重啟就是程式自動關閉後在重新開啟:

一般一個qt程式main函數如下:

int main(int argc, char* argv[])

{

     QApplication app(argc, argv);

     QWidget widget;

     widget.resize(400, 400);

     widget.show();

     return app.exec();

}

一 . 關閉程式

    widget 組建show()之後就進入應用程式的事件迴圈 app.exec();   所以讓程式自動關閉就需要讓應用程式退出事件迴圈,怎樣退出呢? 有兩種方案,第一,直接用Qt內建的全域變數qApp執行qApp->exit()或者qApp->quit(), 第二種方案是利用qt的一個內建屬性,quitOnLastWindowClosed,就是當GUI最後一個視窗關閉時,GUI程式會發出一個最後視窗關閉的訊號,應用程式接到這個訊號後就準備做退出事件迴圈的操作。關閉所有視窗的辦法是 QApplication::closeAllWindows()

二. 重啟

    QProcess::startDetached(qApp->applicationFilePath(), QStringList());

所以根據以上思路就可以得到自動關閉重啟的代碼:

void    xxxx:onRestart()

{

    qApp->quit();   // 或者   aApp->closeAllWindows();

    QProcess::startDetached(qApp->applicationFilePath(), QStringList());

}

看到一種有意思的方法是在onRestart()中只做退出操作,然後在main函數中做重啟操作。

void xxx:onRestart()

{

    qApp->exit(777);

}

然後main函數中:

int main(int argc, char* argv[])

{

     QApplication app(argc, argv);

     QWidget widget;

     widget.resize(400, 400);

     widget.show();

     int e = app.exec();

     if(e == 777)

    {

       QProcess::startDetached(qApp->applicationFilePath(), QStringList()); 

        return 0;

    }

    return e;

}

 

http://www.cnblogs.com/thorngirl/articles/3940888.html

 

qt 自動重啟(兩種方法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.