-1

I was making a program with Python 3.7 & PyQt5 5.15.4, and I have a sudden crash issue. This is a simplified version which shows this phenomena.

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QDialog, QVBoxLayout, QApplication


class WindowA(QWidget):
    def __init__(self):
        super().__init__()
        self.make_layout()

    def make_layout(self):
        vbox = QVBoxLayout()
        self.setLayout(vbox)


class LoginDialog(QDialog):
    def __init__(self):
        super().__init__()

        self.btn_login = QPushButton('Login')
        self.btn_login.clicked.connect(self.btn_login_clicked)

        vbox = QVBoxLayout()
        vbox.addWidget(self.btn_login)
        self.setLayout(vbox)

    def btn_login_clicked(self):
        self.accept()
        main_window = WindowA()
        main_window.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    login_dialog = LoginDialog()
    login_dialog.show()
    sys.exit(app.exec_())

This is what I intended:

  1. The program starts with LoginDialog, which contains one login button.
  2. If I push the button, WindowA appears.

However, if I run the code, when I push the login button in LoginDialog, WindowA flashes and the program terminates with no error message.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

There is no crash, both windows close so the program is finished running.

  • LoginDialog closes because QDialog.accept() causes the dialog to close.
  • WindowA gets garbage collected as soon as the function returns. Use an instance variable so it stays in scope.
def btn_login_clicked(self):
    self.main_window = WindowA()
    self.main_window.show()
alec
  • 5,799
  • 1
  • 7
  • 20