Search code examples
pythonpyqtpyqt5qt-designer

PyQt: how to load multiple .ui Files from Qt Designer


I want to add startup window that when I click button, it will open another window and close current window. For each window, it has seperated UI which created from Qt Designer in .ui form.

I load both .ui file via uic.loadUiType(). The first window(first UI) can normally show its UI but when I click button to go to another window, another UI (second UI) doesn't work. It likes open blank window.

Another problem is if I load first UI and then change to second UI (delete that Class and change to another Class, also delete uic.loadUiType()), the second UI still doesn't work (show blank window)

Please help... I research before create this question but can't find the answer.

Here's my code. How can I fix it?

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5 import uic

#load both ui file
uifile_1 = 'UI/openPage.ui'
form_1, base_1 = uic.loadUiType(uifile_1)

uifile_2 = 'UI/mainPage.ui'
form_2, base_2 = uic.loadUiType(uifile_2)

class Example(base_1, form_1):
    def __init__(self):
        super(base_1,self).__init__()
        self.setupUi(self)
        self.startButton.clicked.connect(self.change)

    def change(self):
        self.main = MainPage()
        self.main.show()

class MainPage(base_2, form_2):
    def __int__(self):
        super(base_2, self).__init__()
        self.setupUi(self)

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

Solution

  • First you have an error, you must change __int__ to __init__. To close the window call the close() method.

    import sys
    from PyQt5.QtWidgets import QApplication, QWidget
    from PyQt5.QtGui import QIcon
    from PyQt5 import uic
    
    #load both ui file
    uifile_1 = 'UI/openPage.ui'
    form_1, base_1 = uic.loadUiType(uifile_1)
    
    uifile_2 = 'UI/mainPage.ui'
    form_2, base_2 = uic.loadUiType(uifile_2)
    
    class Example(base_1, form_1):
        def __init__(self):
            super(base_1,self).__init__()
            self.setupUi(self)
            self.startButton.clicked.connect(self.change)
    
        def change(self):
            self.main = MainPage()
            self.main.show()
            self.close()
    
    class MainPage(base_2, form_2):
        def __init__(self):
            super(base_2, self).__init__()
            self.setupUi(self)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        ex = Example()
        ex.show()
        sys.exit(app.exec_())