Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

qt

pyside

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

like image 307
RootRaven Avatar asked Dec 11 '22 09:12

RootRaven


1 Answers

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.

like image 101
three_pineapples Avatar answered May 13 '23 02:05

three_pineapples