重启QApplication的正确方法是什么?

时间:2013-06-03 08:06:39

标签: python qt pyqt pyside

我正在使用PySide,并寻求一种方法来重启我的Qt应用程序。这取决于python,还是必须由Qt控制?

由ROSTYSLAV的建议BELLOW:

class MyAppMainWindow(QMainWindow):
    def __init__(self):

        self.EXIT_CODE_REBOOT = -15123123
        exit_code = self.EXIT_CODE_REBOOT

    def slotReboot(self):

        print "Performing application reboot.."
        qApp.exit( self.EXIT_CODE_REBOOT )

def main():
    currentExitCode = 0
    app = QApplication(sys.argv)
    ex = MyAppMainWindow()

    while currentExitCode == ex.EXIT_CODE_REBOOT :
        currentExitCode = app.exec_()

        return currentExitCode

if __name__ == '__main__':
    main()

显然我并不完全明白。请帮助。

2 个答案:

答案 0 :(得分:2)

Qt Wiki提供了一个关于如何使应用程序可重启的好方法。 该方法基于QApplication实例的重新创建,而不是杀死当前进程。

它可以很容易地被PySide采用,如下一个片段所示:

EXIT_CODE_REBOOT = -15123123 # you can use any unique value here
exit_code = EXIT_CODE_REBOOT # Just for making cycle run for the first time

while exit_code == EXIT_CODE_REBOOT:
    exit_code = 0                       # error code - no errors happened
    app = QApplication(sys.argv)
    ...
    exit_code = app.exec() 

您需要在完成应用之前通过QApplication预先设定的API设置正确的退出代码。您可以在创建新的应用程序实例时挂接新配置或任何您需要的内容。

答案 1 :(得分:1)

这个话题很老了,但我发现没有提供适当的解决方案。所以这里(根据Rostyslav Dzinko的建议):

EXIT_CODE_REBOOT = -11231351

from PySide import QtGui, QtCore
import sys

class MyApp(QtGui.QMainWindow):

    def __init__(self, parent=None):       
        super(MyApp, self).__init__(parent)
    def restart (self):            
        #DO stuff before restarting here            
        return QtCore.QCoreApplication.exit( EXIT_CODE_REBOOT )            

def start_app():

    exit_code = 0
    while True:
        try:
            app = QtGui.QApplication(sys.argv)
        except RuntimeError:
            app = QtCore.QCoreApplication.instance()            
        myap = MyApp()
        myap.show()            
        exit_code = app.exec_()            
        if exit_code != EXIT_CODE_REBOOT:
            break        
    return exit_code


if __name__ == '__main__':
    start_app()
相关问题