从布局中按名称获取小部件 [英] get widgets by name from layout
问题描述
如果我想从 python Qt 的布局中获取特定的小部件,我应该如何进行?
How should I proceed if I want to get an especific widget from a layout in python Qt?
到目前为止我做了什么:
What I have done so far:
for i in range(self.ui.horizontalLayout_14.count()):
#here it does fail
name = self.ui.horizontalLayout_14.itemAt(i).objectName()
#if the above would had worked, then I could do something like this for example
if "button" in name:
self.ui.horizontalLayout_14.itemAt(i).widget().close()
请注意,例如,我使用的是 button
,但它可能是布局、lineEdit 或组合框、标签等中的任何小部件,但并非全部.>
Note that, for the example, I am using button
but It might be whatever widget inside the layout, lineEdit, or comboBox, labels, etc etc, but not all of them though.
推荐答案
问题在于 itemAt()
函数返回 QLayoutItem
而不是小部件.所以你必须调用 QLayoutItem::widget()
函数来获取包含的小部件,即:
The problem is that itemAt()
function returns the QLayoutItem
and not a widget. So you have to call the QLayoutItem::widget()
function to get the containing widget, i.e.:
name = self.ui.horizontalLayout_14.itemAt(i).widget().objectName()
更新
但是,使用 QObject::findChild()
函数可以更轻松地完成同样的工作.即:
However, you can do the same much easier with using the QObject::findChild()
function. I.e.:
widget = self.ui.findChild(QPushButton, "button")
# Check whether the returned widget is null...
这篇关于从布局中按名称获取小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!