Search code examples
pyqtpyqt5pysidepyside6pyqt6

How do I destroy widget on button press and open MainWindow?


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.


Solution

  • 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()