7

I have a main window and I want to open a another window (not a dialog) on button press. My problem is that the new window closes almost immediately after it opens. I have read the available articles, and tried to implement the solutions, but seem to have no luck. This is my entire code:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MainWindow (QMainWindow):
    def __init__(self):
        win = QWidget()
        win.adjustSize()
        grid=QGridLayout()
        grid.setRowStretch(0, 1)
        grid.setRowStretch(1, 1)
        grid.setRowStretch(5, 1)
        for i in range(0,5):
            for j in range(0,4):
                if i==0 and j==2:
                    l1=grid.addWidget(QLabel("Choose an option:"),i,j, 2, 2)
                if i==2 and j==1:
                    b1= QPushButton("Get Best Match")
                    grid.addWidget(b1,i,j)
                elif i==2 and j==2:
                    b2=QPushButton("Button2")
                    grid.addWidget(b2,i,j)
                elif i==2 and j==3:
                    b3=QPushButton("Button3")
                    grid.addWidget(b3,i,j)
        b5=grid.addWidget(QLabel(""),3,4) 
        b4=QPushButton("Button4")
        grid.addWidget(b4,2,4)
        w1=b1.clicked.connect(window1)
        b2.clicked.connect(Win2)
        b3.clicked.connect(Win3)
        b4.clicked.connect(Win4)            
        win.setLayout(grid)
        win.setGeometry(100,100,width//2,height//2,)
        win.setWindowTitle("PYQT")
        win.show()
        win.setStyleSheet("""
        .QPushButton {
        height: 30px ;
        width: 20px ; 
        }
        .QLabel {
        qproperty-alignment: AlignCenter;
        font-size:12pt
         }

         """)
        sys.exit(app.exec_())

class window1():
    def __init__(self, pressed):
        super(window1, self).__init__()
        win1 = QWidget()
        win1.adjustSize()
        win1.setGeometry(100,100,width//2,height//2,)
        win1.setWindowTitle("Get Best Match")
        win1.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    screen_resolution = app.desktop().screenGeometry()
    width, height = screen_resolution.width(), screen_resolution.height()
    main=MainWindow()

Could someone please help me with this? I have been stuck for some time now.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Sarah
  • 161
  • 1
  • 3
  • 11
  • 1
    Does this answer your question? [PyQt window closes immediately after opening](https://stackoverflow.com/questions/16069713/pyqt-window-closes-immediately-after-opening) – user202729 Feb 04 '21 at 03:14

1 Answers1

24

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.

user3419537
  • 4,740
  • 2
  • 24
  • 42
  • My problem is that when I click the button GetBestMatch, the new window opens up just for the second and then closes. But the main window always remains open (which I want). I implemented the changes suggested by you, but it didn't seem to work – Sarah Feb 15 '17 at 12:49
  • Ok, it wasn't clear which window you were referring to. On closer inspection your problem is two-fold. Firstly you have the same problem as I described in your `window1` class that is referenced by the "get best match" button. The other problem is that you pass the class name when connecting signals. This is essentially passing the class constructor as a slot, which once again discards the newly created window. You need to connect to a function that creates the window and stores a reference – user3419537 Feb 15 '17 at 13:03
  • Also, the `app.exec_()` inside of `sys.exit(app.exec_())` starts the Qt event loop. It should not be inside of any class. Move it to the end of your code – user3419537 Feb 15 '17 at 13:06
  • Hi @user3419537 Could you please explain with the help of the tweaks in the code? So that I understand better. I did try moving the sys.exit(app.exec_()) to the if name =main part and then even the main window closed after opening. Also, I added self to the window1 code and did not change the output either – Sarah Feb 15 '17 at 13:58