Green Cell
Green Cell

Reputation: 4777

PySide get QObject's parent anywhere in its hierarchy

Consider I have a class with this kind of structure (CustomClass may/may not be on top of the hierarchy):

CustomClass

.. QTabWidget

.... QWidget

...... QTreeView

In QTreeView I have a function that is trying to refer back to CustomClass. Right now in order to do this I need to do: self.parent().parent().parent().

Although this works it just feels very sloppy, and if I ever need to change the structure this will fail. Is there some other way to get CustomClass? Usually I would pass an instance of it during its constructor which I can call directly, but wondering what's the best practice to go about this.

Upvotes: 0

Views: 1137

Answers (2)

strubbly
strubbly

Reputation: 3477

The question title leads to a very direct answer. The window() method on QWidget returns the ancestor widget that has (or could have) a window-system frame: typically the "top-level" widget that you want to find. The docs give changing the window title as a canonical use case:

self.window().setWindowTitle(newTitle)

It returns self if the Qwidget is a window itself.

However, the text of your question and your own answer give an alternative interpretation: you might alternatively want to find the ancestor that is of a particular type even if it is not the top level widget. In this case, iterating up through the ancestors is typically the right solution, pretty much as you have written for yourself. So that would be something like:

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

Note that you should usually use isinstance rather than type() == because the former correctly handles sub-classes.

Also note that this code will return None if no CustomClass is found which may or may not be what you want ...

Upvotes: 1

Green Cell
Green Cell

Reputation: 4777

This feels like a decent procedural way to get it:

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

Any other answers are still welcome :)

Upvotes: 0

Related Questions