Close and Open new Window PYQT5

2020-04-19 06:00发布

问题:

I would like to press a button in a window and close that window,after that open a new window

How can I do it?

I already tried it but it sends this message the console:

QCoreApplication::exec: The event loop is already running

class Window(QWidget):
    def __init__(self,parent = None):
        super().__init__(parent)
        self.title = 'pySim Z-eighty'
        self.left = 0
        self.top = 0
        self.width = 1200
        self.height = 3000
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.button = QPushButton("Z80")
        self.button1 = QPushButton()
        self.button2 = QPushButton()
        self.container =    QWidget()
        self.layout = QGridLayout()
        self.layout.addWidget(self.button1, 1, 0)
        self.layout.addWidget(self.button, 1, 1)
        self.layout.addWidget(self.button2, 1, 2)
        self.container.setLayout(self.layout)
        self.layoutPrincipal = QBoxLayout(0)
        self.layoutPrincipal.addWidget(self.container)
        self.setLayout(self.layoutPrincipal)
        self.button.pressed.connect(self.IniciarInterfaz)

    def IniciarInterfaz(self):
        self.hide()
        app = QApplication(sys.argv)
        ex = mainWindow()
        ex.setStyleSheet("background-color: #fff")
        ex.show()
        sys.exit(app.exec_())

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

My main problem is when i pressed the button I can't open the new window

回答1:

There can only be one QApplication within the PyQt application, so if you already created it, do not do it again.

Another problem is that the variables exist only within the context, in your case mainWindow, so at the end of the function StartInterface will eliminate this variable and the window, the solution is to make the mainWindow member of the class, so the context will be the class and no longer the function, so it will stay correctly.

def IniciarInterfaz(self):
    self.hide()
    self.ex = mainWindow()
    self.ex.setStyleSheet("background-color: #fff")
    self.ex.show()


回答2:

PYQT No open and close method,...

hide() and show() method you can use buttons what ever you want,...

def PlatformType_Clicked(self):
    dialog.hide()
    dialog1.show()