Search code examples
pythonqtpysideqtguiqmainwindow

How to import mainwindow (.ui file) using PySide


I'm doing a python project and design its interface using PySide. The problem is how can I import mainwindow (.ui file) from Qt Designer using PySide. My class is inherited from QtGui.QMainWindow.

Thank you for your answer. ^^


Solution

  • Let's say the top-level object in Qt Designer is named MainWindow.

    When you use pyside-uic to generate the GUI module, it will create a class called Ui_MainWindow. It is this class that you need to import into your main application. The imported class has a setupUi method, which is used to inject the GUI into an instance of the top-level class from Qt Designer. So the basic code to do this should look something like this:

    from PySide import QtCore, QtGui
    from mainwindow import Ui_MainWindow
    
    class MainWindow(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            self.ui = Ui_MainWindow.setupUi(self)
    

    With that in place, you can access the widgets from Qt Designer like this:

           # connect a button to its handler
           self.ui.pushButton.clicked.connect(self.handleButtonClicked)
    

    To run the application, you can do:

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