change QMainWindow PyQt5 after pressed button

2019-07-13 12:29发布

问题:

I have generated my UI with Qt Designer:

like this

I have used the .ui file with the following python code:

Ui_MainWindow, QtBaseClass = uic.loadUiType("vault.ui")
Ui_Credentials, QtBaseClass = uic.loadUiType("credentials.ui")

class Credentials(QMainWindow):
    def __init__(self):
        super(Credentials, self).__init__()
        self.ui = Ui_Credentials()
        self.ui.setupUi(self)


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.load.clicked.connect(self.loadVault)
        self.ui.next.clicked.connect(self.next)

        self.controller = CLI(....)
        self.loadVault()

    def loadVault(self):
        self.ui.vault.clear()
        vaults = self.controller.listVaults()
        for vault in vaults:
            item = QListWidgetItem(vault)
            self.ui.vault.addItem(item)

    def next(self):

        print(self.ui.vault.currentItem().text())
        window = Credentials()
        window.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

I have tried to change the window when the button next is pressed by created a new class and using a different ui file.

I found this stackoverflow post where this is a similar problem but the code is this post doesn't use a .ui and I did not manage to have a working code with .ui file. I have succeeded to have a new window when I don't use my ui file.

Someone know how can I deal with this ? Is it not adviced to use .ui file?

回答1:

The solution that I propose is similar to my previous answer, the objective is to change the graphical part so we will use the function setupUI () that generates that part.

When we press the next button, you must change it back with that function.

Ui_MainWindow, _ = uic.loadUiType("vault.ui")
Ui_Credentials, _ = uic.loadUiType("credentials.ui")


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.startMainWindow()

    def startMainWindow(self):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.next.clicked.connect(self.startCredentials)

    def startCredentials(self):
        self.ui = Ui_Credentials()
        self.ui.setupUi(self)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())