Important: Please read the Qt Code of Conduct -

Best Practice to load .ui files

  • I've seen a lot of mixed methods on the web for importing ui into a custom class inhered from a QMainWindow or widget. In this example let us use a QMainWindow where I'd be build a large application. I'm trying to find the best practices for using a ui file.

    I'm aware of the conversion of the ui to .py files with pyqt5, but I really like the flexibility to pop into designer and update the ui file and see instance changes.
    So far I've been using this method:

    from PySide2 import QtCore, QtWidgets, QtUiTools
    import os
    class ImportUi(QtWidgets.QMainWindow):
        def __init__(self):
            loader = QtUiTools.QUiLoader()
            script_dir = os.path.dirname(__file__)
            main_ui_path = 'gui.ui'
            self.ui = loader.load(os.path.join(script_dir, main_ui_path))
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        gui = ImportUi()
        rec = app.exec_()

    Is there a way the ImportUi class can inherit from the returned QMainWindow from the loader? So I would not have to store the ui in the class instance variable? Basically is there a way i could access self.named_table_widget without having to go through the self.ui? I've seen you can pass a parent widget to the .load() argument, but using "self" didn't give me the results i was hoping for.
    Or is there a completely better approach to all of this?


  • Lifetime Qt Champion


    No there is not. QUiLoader::load returns a new QWidget that you can then use. The parent parameter just makes said widget a child of the parent.

  • Thanks SGaist, just wanted to make sure I wasn't missing something.

  • @alom said in Best Practice to load .ui files:

    Thanks SGaist, just wanted to make sure I wasn't missing something

    If your issue is solved, please don't forget to mark your post as such!.

Log in to reply