pythonpyqt5qt-designerui-design

Close current window and open new one in conditions pyqt


How to close the current window and open new window if condition is true(without any button clicked) and run the hole script again. I have tried so many method but not success

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
    .....
 
if __name__ == "__main__":
    # print(deivce_data)
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
    if deivce_data == data:
        '''if this condition is true close the current window and run script again'''

Solution

  • You can do this by controlling the execution handle of QApplication().

    import sys
    from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
    
    
    class Ui_MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
    
    
    if __name__ == "__main__":
        # print(deivce_data)
        app1 = QApplication(sys.argv)
        ui1 = Ui_MainWindow()
        ui1.setWindowTitle("My App1")
        ui1.show()
        finish_app1 = app1.exec_()
    
        if True:
            '''if this condition is true close the current window and run script again'''
            app2 = QApplication(sys.argv)
            ui2 = Ui_MainWindow()
            ui2.setWindowTitle("My App2")
            ui2.show()
            finish_app2 = app2.exec_()
            handle_finish = finish_app2
        else:
            handle_finish = finish_app1
    
        sys.exit(handle_finish)
    

    Hope this helps.