PySide在其层次结构中的任何位置获取QObject的父级

时间:2015-12-01 07:03:37

标签: python pyqt pyside

考虑我有一个具有这种结构的类(CustomClass可能/可能不在层次结构之上):

CustomClass

.. QTabWidget

.... QWidget

...... QTreeView

QTreeView我有一个试图回顾CustomClass的函数。现在,为了做到这一点,我需要做:self.parent().parent().parent()

虽然这样可行,但感觉非常草率,如果我需要改变结构,这将失败。是否有其他方法可以获得CustomClass?通常我会在它的构造函数中传递一个它的实例,我可以直接调用它,但是想知道最好的做法是什么。

2 个答案:

答案 0 :(得分:1)

问题标题可以得到一个非常直接的答案。 window()上的QWidget方法返回具有(或可能具有)窗口系统框架的祖先窗口小部件:通常是您要查找的“顶级”窗口小部件。文档将窗口标题更改为规范用例:

self.window().setWindowTitle(newTitle)

如果self本身就是一个窗口,则返回Qwidget

然而,您的问题的文本和您自己的答案给出了另一种解释:您可能或者想要找到特定类型的祖先,即使它不是顶级小部件。在这种情况下,通过祖先迭代通常是正确的解决方案,就像您为自己编写的那样。所以这就像是:

customClassInst = self.parent()
while customClassInst is not None and not isinstance(customClassInst,CustomClass):
    customClassInst = customClassInst.parent()

请注意,您通常应使用isinstance而不是type() ==,因为前者正确处理子类。

另请注意,如果找不到None,则此代码将返回CustomClass,这可能是您想要的,也可能不是......

答案 1 :(得分:0)

这感觉就像是一种体面的程序方式:

customClassInst = self.parent()
while customClassInst is not None and type(customClassInst) != CustomClass:
    customClassInst = customClassInst.parent()

仍欢迎任何其他答案:)