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

PySide get QObject's parent anywhere in its hierarchy

考虑我有一个具有这种结构的 class(CustomClass may/may 不在层次结构的顶部):

CustomClass

.. QTabWidget

.... QWidget

...... QTreeView

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

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

这感觉是一种不错的程序化方式:

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

仍然欢迎任何其他答案:)

问题标题引出了非常直接的答案。 QWidget return 上的 window() 方法具有(或可能具有)window-system 框架的祖先小部件:通常是您要查找的 "top-level" 小部件.文档将更改 window 标题作为规范用例:

self.window().setWindowTitle(newTitle)

它 returns self 如果 Qwidget 是一个 window 本身。

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

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

请注意,您通常应该使用 isinstance 而不是 type() ==,因为前者可以正确处理 sub-classes.

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