Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restart my pyqt application?

Tags:

pyqt

pyqt4

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

How to restart this code ?

like image 715
Piers Avatar asked Dec 08 '22 00:12

Piers


2 Answers

Let's say you are in MainWindow. Define in the __init__

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

Your slot restart() should contain:

qApp.exit( MainWindow.EXIT_CODE_REBOOT )

and your 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


EDIT: Minimal working example

Instead of a signal/slot, I just re-implemented the keyPressedEvent method.

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
like image 95
ochurlaud Avatar answered Feb 27 '23 13:02

ochurlaud


Below will restart the whole application fully, regardless of frozen or unfrozen packages.

os.execl(sys.executable, sys.executable, *sys.argv)
like image 29
Sina Avatar answered Feb 27 '23 13:02

Sina