Skip to content

PythonObjectTreeModel

Base classes

Name Children Inherits
ColumnItemModel
prettyqt.itemmodels.columnitemmodel
TreeModel with columns defined by ColumnItem classes.

â‹” Inheritance diagram

graph TD
  818836822["itemmodels.PythonObjectTreeModel"]
  3096575510["itemmodels.ColumnItemModel"]
  1030521844["itemmodels.ColumnItemModelMixin"]
  2751680898["builtins.object"]
  2846913429["itemmodels.TreeModel"]
  874904086["core.AbstractItemModel"]
  3882849576["core.AbstractItemModelMixin"]
  3227531497["core.ObjectMixin"]
  1898060022["QtCore.QAbstractItemModel"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  3096575510 --> 818836822
  1030521844 --> 3096575510
  2751680898 --> 1030521844
  2846913429 --> 3096575510
  874904086 --> 2846913429
  3882849576 --> 874904086
  3227531497 --> 3882849576
  2751680898 --> 3227531497
  2751680898 --> 3882849576
  1898060022 --> 874904086
  3984060476 --> 1898060022
  37984305 --> 3984060476
  2751680898 --> 37984305

🛈 DocStrings

Bases: ColumnItemModel

Source code in prettyqt/itemmodels/pythonobjecttreemodel.py
class PythonObjectTreeModel(itemmodels.ColumnItemModel):
    TreeItem = PythonObjectTreeItem
    IS_RECURSIVE = True
    ICON = "mdi.python"
    SUPPORTS = object
    COLUMNS: ClassVar = [
        NameColumn,
        DescriptionColumn,
        PathColumn,
        StrColumn,
        ReprColumn,
        LengthColumn,
        TypeColumn,
        ClassColumn,
        IdColumn,
        AttributeColumn,
        IsCallableColumn,
        IsRoutineColumn,
        IsBuiltinColumn,
        PredicateColumn,
        ModuleColumn,
        # FileColumn,
        # SourceFileColumn,
    ]

    def __init__(self, obj, parent=None):
        super().__init__(obj, self.COLUMNS, show_root=False, parent=parent)

    @classmethod
    def supports(cls, instance) -> bool:
        return True

    def get_path_for_index(self, index: core.ModelIndex) -> str:
        """Get the path for the object referenced by index.

        ### Example:
        ```
        An.example = {"a": [b, c, {"d": e}]} -> path of e: An.example["a"][2]["d"]
        ```
        """
        if not index.isValid():
            return ""
        return self.data_by_index(index).obj_path

    def _fetch_object_children(
        self, treeitem: PythonObjectTreeItem
    ) -> list[PythonObjectTreeItem]:
        """Fetch the children of a Python object.

        Returns: list of PythonObjectTreeItems
        """
        obj_children = []
        path_strings = []
        obj = treeitem.obj
        obj_path = treeitem.obj_path
        if isinstance(obj, list | tuple | set | frozenset):
            obj_children = [(str(i), j) for i, j in enumerate(obj)]
            path_strings = [f"{obj_path}[{i}]" for i, _ in obj_children]
        elif isinstance(obj, Mapping):
            obj_children = list(obj.items())
            path_strings = [f"{obj_path}[{key!r}]" for key, _ in obj_children]

        is_attr_list = [False] * len(obj_children)

        # Object attributes
        try:
            members = sorted(inspect.getmembers(obj), key=lambda x: x[0])
        except Exception:  # noqa: BLE001
            logger.debug("could not get members of %r", obj)
            members = []
        for attr_name, attr_value in members:
            obj_children.append((attr_name, attr_value))
            path_strings.append(f"{obj_path}.{attr_name}" if obj_path else attr_name)
            is_attr_list.append(True)

        return [
            PythonObjectTreeItem(obj=val, name=name, obj_path=p, is_attribute=is_attr)
            for (name, val), p, is_attr in zip(obj_children, path_strings, is_attr_list)
        ]

    def _aux_refresh_tree(self, tree_index: core.ModelIndex):
        """Refresh the tree nodes recursively, auxiliary.

        If the underlying Python object has been changed, we don't want to delete the old
        tree model and create a new one from scratch because this loses all information
        about which nodes are fetched and expanded. Instead the old tree model is updated.
        Using the difflib from the standard library it is determined for a parent node
        which child nodes should be added or removed. This is done based on the node names
        only, not on the node contents (the underlying Python objects). Testing the
        underlying nodes for equality is potentially slow. It is faster to let the
        refreshNode function emit the dataChanged signal for all cells.
        """
        tree_item = self.data_by_index(tree_index)
        if not tree_item.children_fetched:
            return
        old_items = tree_item.children
        new_items = self._fetch_object_children(tree_item)

        old_item_names = [(item.obj_name, item.is_attribute) for item in old_items]
        new_item_names = [(item.obj_name, item.is_attribute) for item in new_items]
        seq_matcher = SequenceMatcher(
            isjunk=None, a=old_item_names, b=new_item_names, autojunk=False
        )
        opcodes = seq_matcher.get_opcodes()

        logger.debug("(reversed) opcodes: %s", list(reversed(opcodes)))

        for tag, i1, i2, j1, j2 in reversed(opcodes):
            match tag:
                case "equal":
                    # when node names are equal is aux_refresh_tree called recursively.
                    for old_row, new_row in zip(
                        range(i1, i2), range(j1, j2), strict=True
                    ):
                        old_items[old_row].obj = new_items[new_row].obj
                        child_index = self.index(old_row, 0, parent=tree_index)
                        self._aux_refresh_tree(child_index)
                    top_left = self.index(i1, 0, tree_index)
                    bottom_right = self.index(i2 - 1, self.columnCount() - 1, tree_index)
                    self.dataChanged.emit(top_left, bottom_right)

                case "replace":
                    # Remove the old item and insert the new. The old item may have child
                    # nodes which indices must be removed by Qt, otherwise it crashes.
                    with self.remove_rows(i1, i2 - 1, tree_index):
                        del tree_item.children[i1:i2]
                    with self.insert_rows(i1, i1 + j2 - j1 - 1, tree_index):
                        tree_item.insert_children(i1, new_items[j1:j2])

                case "delete":
                    with self.remove_rows(i1, i2 - 1, tree_index):
                        del tree_item.children[i1:i2]

                case "insert":
                    with self.insert_rows(i1, i1 + j2 - j1 - 1, tree_index):
                        tree_item.insert_children(i1, new_items[j1:j2])
                case _:
                    msg = f"Invalid tag: {tag}"
                    raise ValueError(msg)

    def refresh_tree(self):
        """Refresh the tree model from the underlying root object.

        Keeps fetched / expanded nodes, emits dataChanged for all fetched rows.
        """
        if self._show_root:
            index = self.createIndex(0, 0, self.inspected_item)
            self.dataChanged.emit(index, self.index(0, self.columnCount() - 1))
        else:
            index = core.ModelIndex()
        self._aux_refresh_tree(index)

get_path_for_index(index: core.ModelIndex) -> str

Get the path for the object referenced by index.

Example:
An.example = {"a": [b, c, {"d": e}]} -> path of e: An.example["a"][2]["d"]
Source code in prettyqt/itemmodels/pythonobjecttreemodel.py
def get_path_for_index(self, index: core.ModelIndex) -> str:
    """Get the path for the object referenced by index.

    ### Example:
    ```
    An.example = {"a": [b, c, {"d": e}]} -> path of e: An.example["a"][2]["d"]
    ```
    """
    if not index.isValid():
        return ""
    return self.data_by_index(index).obj_path

refresh_tree()

Refresh the tree model from the underlying root object.

Keeps fetched / expanded nodes, emits dataChanged for all fetched rows.

Source code in prettyqt/itemmodels/pythonobjecttreemodel.py
def refresh_tree(self):
    """Refresh the tree model from the underlying root object.

    Keeps fetched / expanded nodes, emits dataChanged for all fetched rows.
    """
    if self._show_root:
        index = self.createIndex(0, 0, self.inspected_item)
        self.dataChanged.emit(index, self.index(0, self.columnCount() - 1))
    else:
        index = core.ModelIndex()
    self._aux_refresh_tree(index)

:fa-brands-github: Show source on GitHub