Skip to content

AstViewer

Qt Base Class: QSplitter

Signature: QSplitter(self, arg__1: PySide6.QtCore.Qt.Orientation, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None QSplitter(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None

Base classes

Name Children Inherits
Splitter
prettyqt.widgets.splitter

⋔ Inheritance diagram

graph TD
  1473367156528["custom_widgets.AstViewer"]
  1473296394480["widgets.Splitter"]
  1473296384720["widgets.SplitterMixin"]
  1473293662864["widgets.FrameMixin"]
  1473293688240["widgets.WidgetMixin"]
  1473299815024["core.ObjectMixin"]
  140713234304496["builtins.object"]
  1473245548480["gui.PaintDeviceMixin"]
  1473290624224["QtWidgets.QSplitter"]
  1473290626176["QtWidgets.QFrame"]
  1473290849680["QtWidgets.QWidget"]
  1473288842240["QtCore.QObject"]
  1473291690208["Shiboken.Object"]
  1473300082368["QtGui.QPaintDevice"]
  1473296394480 --> 1473367156528
  1473296384720 --> 1473296394480
  1473293662864 --> 1473296384720
  1473293688240 --> 1473293662864
  1473299815024 --> 1473293688240
  140713234304496 --> 1473299815024
  1473245548480 --> 1473293688240
  140713234304496 --> 1473245548480
  1473290624224 --> 1473296394480
  1473290626176 --> 1473290624224
  1473290849680 --> 1473290626176
  1473288842240 --> 1473290849680
  1473291690208 --> 1473288842240
  140713234304496 --> 1473291690208
  1473300082368 --> 1473290849680
  1473291690208 --> 1473300082368

🛈 DocStrings

Bases: Splitter

Widget which displays an AST Tree next to the corresponding source code.

Selecting a node in the tree will highlight the corresponing text section in source.

widget = custom_widgets.AstViewer()
widget.show()

Image title

AstViewer widget
Source code in prettyqt\custom_widgets\astviewer.py
class AstViewer(widgets.Splitter):
    """Widget which displays an AST Tree next to the corresponding source code.

    Selecting a node in the tree will highlight the corresponing text section in source.

    ``` py
    widget = custom_widgets.AstViewer()
    widget.show()
    ```

    <figure markdown>
      ![Image title](../../images/astviewer.png)
      <figcaption>AstViewer widget</figcaption>
    </figure>
    """

    def __init__(
        self,
        object_name="ast_viewer",
        **kwargs,
    ):
        super().__init__(orientation="horizontal", object_name=object_name, **kwargs)
        self.tree = widgets.TreeView()
        self.ast_textedit = widgets.PlainTextEdit()
        self.tabwidget = widgets.TabWidget()
        self.tabwidget.add_tab(self.tree, "Tree")
        self.tabwidget.add_tab(self.ast_textedit, "Dumped")

        self.textedit = custom_widgets.CodeEditor()
        self.textedit.set_syntaxhighlighter("python")
        self.textedit.textChanged.connect(self._on_text_change)
        self.add(self.tabwidget)
        self.add(self.textedit)

    def _on_text_change(self):
        self.set_ast(self.textedit.get_value())

    def _on_current_change(self, new_index: core.ModelIndex, _):
        node = new_index.data(constants.USER_ROLE)
        if not hasattr(node, "lineno"):
            return
        with self.textedit.selecter.current_cursor() as cursor:
            cursor.select_text(
                (node.lineno - 1, node.col_offset),
                (node.end_lineno - 1, node.end_col_offset),
            )

    def set_ast(self, ast_or_str: str | ast.AST):
        if self.tree.model() is None:
            model = itemmodels.AstModel(ast_or_str, show_root=True, parent=self.tree)
            self.tree.set_model(model)
            self.tree.selectionModel().currentChanged.connect(self._on_current_change)
        else:
            self.tree.model().set_ast(ast_or_str)
        self.tree.show_root(False)
        self.tree.expandAll()
        ast_tree = self.tree.get_model(skip_proxies=True).ast_tree
        text = ast_or_str if isinstance(ast_or_str, str) else ast.unparse(ast_or_str)
        with self.textedit.signals_blocked():
            self.textedit.set_text(text)
        dumped = ast.dump(ast_tree, indent=4)
        self.ast_textedit.set_text(dumped)

    def rename_variable(
        self,
        old: str,
        new: str,
        ignore: list[str] | None = None,
        scope: list[str] | None = None,
    ):
        if scope is None:
            scope = ["main"]
        if ignore is None:
            ignore = []
        tree = self.tree.get_model(skip_proxies=True).ast_tree
        for i in ast.iter_fields(tree):
            if not isinstance(a := getattr(tree, i), list):
                if a == old and not {*scope} & {*ignore}:
                    setattr(tree, i, new)
            n = a if isinstance(a, list) else [a]
            s = [tree.name] if tree.__class__.__name__.endswith("Def") else scope
            for j in n:
                if isinstance(j, ast.AST):
                    self.rename_variable(j, old, new, ignore, s)

⌗ Property table

Qt Property Type Doc
objectName QString
modal bool
windowModality Qt::WindowModality
enabled bool
geometry QRect
frameGeometry QRect
normalGeometry QRect
x int
y int
pos QPoint
frameSize QSize
size QSize
width int
height int
rect QRect
childrenRect QRect
childrenRegion QRegion
sizePolicy QSizePolicy
minimumSize QSize
maximumSize QSize
minimumWidth int
minimumHeight int
maximumWidth int
maximumHeight int
sizeIncrement QSize
baseSize QSize
palette QPalette
font QFont
cursor QCursor
mouseTracking bool
tabletTracking bool
isActiveWindow bool
focusPolicy Qt::FocusPolicy
focus bool
contextMenuPolicy Qt::ContextMenuPolicy
updatesEnabled bool
visible bool
minimized bool
maximized bool
fullScreen bool
sizeHint QSize
minimumSizeHint QSize
acceptDrops bool
windowTitle QString
windowIcon QIcon
windowIconText QString
windowOpacity double
windowModified bool
toolTip QString
toolTipDuration int
statusTip QString
whatsThis QString
accessibleName QString
accessibleDescription QString
layoutDirection Qt::LayoutDirection
autoFillBackground bool
styleSheet QString
locale QLocale
windowFilePath QString
inputMethodHints QFlags
frameShape QFrame::Shape
frameShadow QFrame::Shadow
lineWidth int
midLineWidth int
frameWidth int
frameRect QRect
orientation Qt::Orientation
opaqueResize bool
handleWidth int
childrenCollapsible bool