python - PySide:如何获取包含给定小部件的布局?

标签 python pyside

从给定的小部件中,是否可以获得包含它的布局?

我正在做一个动态表单,我的小部件层次结构如下所示:

QDialogBox
|- QVBoxLayout
  |- QHBoxLayout 1
    |- Widget 1
    |- Widget 2
    |- ...
  |- QHBoxLayout 2
    |- Widget 1
    |- Widget 2
    |- ...
  |- ...

如果我收到来自 Widget 1Widget 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/

相关文章:

python - 在远程IPython集群上运行作业时出现"execution_count"错误

python - 使用 python 的类型库指定不止一种可能的类型

python - qt5(和 python)——如何获取用户操作系统的默认缩略图大小

java - 在 Jython 中导入 Paramiko

python - 提取 Panda Series 列表中的倒数第二个元素

从 Shell 文件启动时 Python 脚本无法运行,但从终端启动时可以运行

python - 如何使嵌入式Python解释器的本地空间与全局空间共享一些变量

python - 获取QTextEdit选择的边界框

Python 'called with the wrong argument type' 错误

python - PySide *任何*方法调用 - 信号和插槽