Replacing the existing MainWindow with a new window with Python, PyQt, Qt Designer

Shahbaj Sayyad picture Shahbaj Sayyad · Oct 2, 2016 · Viewed 11.6k times · Source

I'm new to Python GUI programming I'm have trouble making a GUI app. I have a main window with only a button widget on it. What i want to know is how to replace the existing window with a new window when an event occurs (such as a button click).
An answer to a similar question here Replace CentralWidget in MainWindow, suggests using QStackedWidgets but they did not use Qt Designer to make their GUI apps whereas I have two .py files, one is the main window file and the other of window that i want to show after a button press take place, hence i don't know how to combine these two in my main.py file. For Example my main window looks like this:
Main Window
And after clicking on the button it should replace the existing window with this:
New Window
I would also like to know if the second window should be of type QStackedWindow, QDialog or QWidget?
Here is my main.py code

from PyQt4 import QtGui
import sys
import design, design1
import os

class ExampleApp(QtGui.QMainWindow, design.Ui_MainWindow):
    def __init__(self, parent=None):
        super(ExampleApp, self).__init__(parent)
        self.setupUi(self)
        self.btnBrowse.clicked.connect(self.doSomething)


    def doSomething(self):
        # Code to replace the main window with a new window
        pass


def main():
    app = QtGui.QApplication(sys.argv)
    form = ExampleApp()
    form.show()
    app.exec_()


if __name__ == '__main__':
    main()

Answer

Brendan Abel picture Brendan Abel · Oct 3, 2016

You probably don't want to actually create and delete a bunch of windows, but if you really want to, you could do it like this

def doSomething(self):
    # Code to replace the main window with a new window
    window = OtherWindow()
    window.show()
    self.close()

The in the OtherWindow class

class OtherWindow(...):
    ...
    def doSomething(self):
        window = ExampleApp()
        window.show()
        self.close()

You actually probably don't want to do this. It would be much better if you simply created 1 main window, with a QStackedWidget and put the different controls and widgets on different tabs of the stacked widget and just switch between them in the same window.