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
如何重启此代码?
答案 0 :(得分:6)
假设你在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
方法而不是信号/插槽。
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
答案 1 :(得分:1)
我在重复的主题 (How to reboot PyQt5 application) 中回答了相同的问题。
这个想法是关闭(或忘记)QMainWindow 并重新创建它。
如果你只是“show()”一个小部件,同样的想法也可以。
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()