从给定的小部件中,是否可以获得包含它的布局?
我正在做一个动态表单,我的小部件层次结构如下所示:
QDialogBox
|- QVBoxLayout
|- QHBoxLayout 1
|- Widget 1
|- Widget 2
|- ...
|- QHBoxLayout 2
|- Widget 1
|- Widget 2
|- ...
|- ...
如果我收到来自 Widget 1
或 Widget 2
的信号,我可以使用 sender()
函数识别它。我希望能够调整同一行其他小部件的一些属性。如何获取对包含给定小部件的 QHBoxLayout
的引用?
parent()
属性为我提供了 QDialogBox
,因为小部件的父级不能是布局。 layout()
属性给我 None
,因为它指的是包含的布局,而不是包含的布局。
最佳答案
在您的情况下,以下内容应该有效(我在类似的设置上进行了测试):
# Starting from Widget_1 get a list of horizontal layouts contained by QVBoxLayout
# Widget_1.parent() returns the QDialogBox
# .layout() returns the containing QVBoxLayout
# children returns layouts in QVBoxLayout, including QHBoxLayout 1-N
# if you know that there are only QHBoxLayouts, you don't need to filter
hlayouts = [layout for layout in Widget_1.parent().layout().children()
if type(layout) == PySide.QtGui.QHBoxLayout]
def layout_widgets(layout):
"""Get widgets contained in layout"""
return [layout.itemAt(i).widget() for i in range(layout.count())]
# then find hlayout containing Widget_1
my_layout = next((l for l in hlayouts if Widget_1 in layout_widgets(l)), None)
我正在使用 next() 查找包含您的小部件的第一个布局(请参阅 https://stackoverflow.com/a/2748753/532513 )。为了提高可读性,您可以使用 for 循环,但 next() 更干净。
关于python - PySide:如何获取包含给定小部件的布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16652578/