0
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QMainWindow


import sys
class wid(QWidget):
    def __init__(self):
        super().__init__()
        self.done = False
        self.layoutt = QVBoxLayout()
        self.button = QPushButton("Click me")
        self.layoutt.addWidget(self.button)
        self.setLayout(self.layoutt)
        self.button.clicked.connect(self.click)

    def click(self):
        m = MainWindow()
        m.show()
        self.destroy()


class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.button = QPushButton("test")
        self.setCentralWidget(self.button)


app = QApplication(sys.argv)

m = wid()
m.show()

app.exec()  

I was expecting that when I pressed the button in the wid class, the widget would be destroyed which works fine, but I was also expecting the MainWindow class to show up. This is to be used for a simple login system where the login is managed by the widget which does some backend stuff and if every thing is correct, It should destroy itself and then give access to the main application which is a QMainWindow. Can someone please help me thank you in advance.

relu
  • 11
  • 2

2 Answers2

0

There are probably better ways to achieve what you want, but this simple fix will make the example code work as intended.

def click(self):
    global m
    m = MainWindow()
    m.show()
    self.deleteLater()

If you want to assign to global variables from a local scope you have to use global.
also, it's usually better to use deleteLater() than destroy()

mahkitah
  • 562
  • 1
  • 6
  • 19
0

Your code doesn't work because m is a local variable that goes out of scope when the function ends, so the window gets destroyed since the only reference gets garbage collected.

While you could declare m as a global variable, that's generally discouraged.

If the main window is going to be the a unique instance and the actual main window of your program, you could simply create it and show it by connecting a custom signal.

class Login(QWidget):
    completed = Signal()
    def __init__(self):
        super().__init__()
        self.layout = QVBoxLayout()
        self.button = QPushButton("Click me")
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)
        self.button.clicked.connect(self.click)

    def click(self):
        self.completed.emit()
        self.deleteLater()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.button = QPushButton("test")
        self.setCentralWidget(self.button)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    login = Login()

    mainWindow = MainWindow()
    login.completed.connect(mainWindow.show)

    login.show()

    sys.exit(app.exec())
musicamante
  • 41,230
  • 6
  • 33
  • 58