Search code examples
pythonpyqtpyqt5pyqt4

How to reboot PyQt5 application


I'm trying to restart my application after an update from the client side. I was able to achieve till the auto update part. I tried to surf on How to restart PyQt application?. There are few similar questions earlier, but none of them have good explanation or example with a button click event. Could you guys help me understand on how to reboot a PyQt application. Basically I want to restart the application from if __name__ == '__main__': everytime there is an update.

Note: AppLogin is my private module I created to handle application login. So basically that would be the landing QDialog once application is opened.

from PyQt5.QtWidgets import *
import sys
import AppLogin

class App:
    def __init__(self):
        btn = QPushButton(main_window)
        btn.setText('close')
        btn.pressed.connect(self.restart)
        main_window.show()

    def restart(self):
        # Here goes the code for restart
        pass


if __name__ == '__main__':
    appctxt = QApplication(sys.argv)
    log_in = AppLogin.Login()
    if log_in.exec_() == QDialog.Accepted:
        main_window = QMainWindow()
        ui = App()
        exit_code = appctxt.exec_()
        sys.exit(exit_code)

Solution

  • The logic is to end the eventloop and launch the application an instant before it closes:

    import sys
    from PyQt5 import QtCore, QtWidgets
    
    
    def restart():
        QtCore.QCoreApplication.quit()
        status = QtCore.QProcess.startDetached(sys.executable, sys.argv)
        print(status)
    
    
    def main():
        app = QtWidgets.QApplication(sys.argv)
    
        print("[PID]:", QtCore.QCoreApplication.applicationPid())
    
        window = QtWidgets.QMainWindow()
        window.show()
    
        button = QtWidgets.QPushButton("Restart")
        button.clicked.connect(restart)
    
        window.setCentralWidget(button)
    
        sys.exit(app.exec_())
    
    
    if __name__ == "__main__":
        main()