Correct way to address Pyside Qt widgets from a .ui file via Python

pyside, python, qt

Solution

Since widget names in Qt Designer must be unique, the hierarchy (at least for getting references to the widgets) is flattened (with no risk of conflict), and so the best way is just to access them via:

loader = QtUiTools.QUiLoader()
ui = loader.load('filename.ui', parent)
my_widget = ui.my_widget_name

This would place a reference to the widget called 'my_widget_name' in Qt Designer in the variable `my_widget`.

I would say the above is the most pythonic way of accessing the widgets created when you load the .ui file.

Problem

I have created a GUI with Qt Designer and accessed it via ``` def loadUiWidget(uifilename, parent=None): loader = QtUiTools.QUiLoader() uifile = QtCore.QFile(uifilename) uifile.open(QtCore.QFile.ReadOnly) ui = loader.load(uifile, parent) uifile.close() return ui MainWindow = loadUiWidget("form.ui") MainWindow.show() children = MainWindow.children() button1 = MainWindow.QPushButton1 ``` "children" does already contain the widgets "QPushButton1", "QTextBrowser1" created in the UI but shouldn't the be accessed by the recoursive findChildren() method? What is an elegant way to access the widgets of the .ui File? References: Find correct instance, Load .ui file

Original source

Related problems