如何重新启动我的 pyqt 应用程序?

How do I restart my pyqt application?

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *


class MainWindow(QMainWindow):
       EXIT_CODE_REBOOT = -123

#constructor
       def __init__(self):
            super().__init__() #call super class constructor
            #above is the constructor ^^^^^^^^^^^
            self.HomePage() #this goes to the homepage function

def HomePage(self):
    #this layout holds the review question 1
    self.quit_button_11 = QPushButton("restart", self)
    self.quit_button_11.clicked.connect(self.restart)

def restart(self):  # function connected to when restart button clicked
    qApp.exit( MainWindow.EXIT_CODE_REBOOT )


if __name__=="__main__":
currentExitCode = MainWindow.EXIT_CODE_REBOOT
while currentExitCode == MainWindow.EXIT_CODE_REBOOT:
    a = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    currentExitCode = a.exec_()
    a = None  # delete the QApplication object

如何重新启动此代码?

假设您在 MainWindow 中。在__init__

中定义
MainWindow.EXIT_CODE_REBOOT = -12345678  # or whatever number not already taken

您的广告位 restart() 应包含:

qApp.exit( MainWindow.EXIT_CODE_REBOOT )

和你的 main:

currentExitCode = MainWindow.EXIT_CODE_REBOOT

while currentExitCode == MainWindow.EXIT_CODE_REBOOT:
    a = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    currentExitCode = a.exec_()

return currentExitCode

[1] https://wiki.qt.io/How_to_make_an_Application_restartable


编辑:最小工作示例

我只是重新实现了 keyPressedEvent 方法,而不是 signal/slot。

import sys
from PyQt4 import QtGui
from PyQt4.QtCore import Qt

class MainWindow(QtGui.QMainWindow):
    EXIT_CODE_REBOOT = -123
    def __init__(self,parent=None):
        QtGui.QMainWindow.__init__(self, parent)

    def keyPressEvent(self,e):
        if (e.key() == Qt.Key_R):
            QtGui.qApp.exit( MainWindow.EXIT_CODE_REBOOT )


if __name__=="__main__":
    currentExitCode = MainWindow.EXIT_CODE_REBOOT
    while currentExitCode == MainWindow.EXIT_CODE_REBOOT:
        a = QtGui.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        currentExitCode = a.exec_()
        a = None  # delete the QApplication object

下面将完全重新启动整个应用程序,无论是否冻结或解冻包。

os.execl(sys.executable, sys.executable, *sys.argv)

我在重复的主题 () 中回答了同样的问题。

想法是关闭(或忘记)QMainWindow 并重新创建它。

如果您只是“显示()”一个小部件,同样的想法也很有效。

import sys
import uuid

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton


class MainWindow(QMainWindow):
    singleton: 'MainWindow' = None

    def __init__(self):
        super().__init__()
        btn = QPushButton(f'RESTART\n{uuid.uuid4()}')
        btn.clicked.connect(MainWindow.restart)
        self.setCentralWidget(btn)
        self.show()

    @staticmethod
    def restart():
        MainWindow.singleton = MainWindow()


def main():
    app = QApplication([])
    MainWindow.restart()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()