问题描述
我使用 Qt Designer 创建了一个 GUI 并通过
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"确实已经包含在 UI 中创建的小部件QPushButton1"、QTextBrowser1",但不应由递归 findChildren() 方法访问吗?
"children" does already contain the widgets "QPushButton1", "QTextBrowser1" created in the UI but shouldn't the be accessed by the recoursive findChildren() method?
访问 .ui 文件的小部件的优雅方式是什么?
What is an elegant way to access the widgets of the .ui File?
推荐答案
由于 Qt Designer 中的小部件名称必须是唯一的,因此层次结构(至少对于获取对小部件的引用)是扁平化的(没有冲突的风险),并且所以最好的方法就是通过以下方式访问它们:
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
这会在变量 my_widget
中放置对 Qt Designer 中名为my_widget_name"的小部件的引用.
This would place a reference to the widget called 'my_widget_name' in Qt Designer in the variable my_widget
.
我认为以上是访问加载 .ui 文件时创建的小部件的最pythonic 方式.
I would say the above is the most pythonic way of accessing the widgets created when you load the .ui file.
这篇关于通过 Python 从 .ui 文件处理 Pyside Qt 小部件的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!