PyQt: Why does new window close immediately after opening it [duplicate]

The window is disappearing because it goes out of scope at the end of your __init__ function. Since there are no further references to it, the python garbage collector removes it.

Usually PyQt objects keep references to their children so this is not a problem. Since you want the widget to open in a separate window, you can’t assign it a parent, so you need to store a reference to it somewhere else. The obvious candidate is the MainWindow class.

You can make win a member of MainWindow by using self.win = QWidget() instead of win = QWidget(). The window will now stay open for the lifetime of MainWindow unless you close it.

You have other problems with your code, but this explains why the window disappears.

Leave a Comment