-2

I want to open a second window when the button is pressed. The window opens and closes immediately. Does someone know what I'm doing wrong?

This is my code:


import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import QMainWindow, QPushButton, QLabel, QApplication

class FirstWindow(QMainWindow):
    def __init__(self):
        super(FirstWindow, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('It\'s working!')
        self.initUI()
    def initUI(self):
        second_screen_btn = QPushButton('Open second screen', self)
        second_screen_btn.setGeometry(250, 100, 100, 100)
        second_screen_btn.clicked.connect(self.open_second_screen)
        self.show()

    def open_second_screen(self):
        second_window = SecondWindow()

class SecondWindow(QMainWindow):

    def __init__(self):
        super(SecondWindow, self).__init__()
        self.setGeometry(100, 100, 500, 300)
        self.setWindowTitle('This is a second window')
        self.initUI()

    def initUI(self):
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = FirstWindow()
    sys.exit(app.exec_())

1 Answers1

2

Simply change your open_second_screen to this:

def open_second_screen(self):
    self.second_window = SecondWindow()
    self.second_window.show()

(And remove the self.show() from the other class, of course)

This is a reccurent issue with PyQt. New windows are garbage collected if not stored in a variable, and the second_window variable is deleted when the function ends, unless you store it as a parameter of your window's instance.

olinox14
  • 6,177
  • 2
  • 22
  • 39