Skip to content

UIInspector

🛈 DocStrings

High-level inspection and screenshot helper bound to a root widget.

Source code in prettyqt/debugging/inspector.py
class UIInspector:
    """High-level inspection and screenshot helper bound to a root widget."""

    def __init__(
        self,
        root: QtWidgets.QWidget,
        out_dir: str | os.PathLike[str] | None = None,
        *,
        app: QtCore.QCoreApplication | None = None,
        ignore_zero_size: Callable[[QtWidgets.QWidget], bool] | None = None,
    ) -> None:
        self.root = root
        self.out_dir = pathlib.Path(out_dir) if out_dir is not None else None
        self._app = app
        self.ignore_zero_size = ignore_zero_size
        self.captures: list[CaptureInfo] = []
        self.collected_warnings: list[LayoutWarning] = []

    @property
    def app(self) -> QtCore.QCoreApplication | None:
        return self._app if self._app is not None else QtCore.QCoreApplication.instance()

    def pump(self, ms: int = 40) -> None:
        """Process Qt events for `ms` milliseconds."""
        pump(self.app, ms=ms)

    def wait_until(
        self,
        predicate: Callable[[], object],
        *,
        timeout_ms: int = 5000,
        interval_ms: int = 10,
    ) -> bool:
        """Process Qt events until `predicate()` returns truthy or times out."""
        return wait_until(
            predicate,
            timeout_ms=timeout_ms,
            interval_ms=interval_ms,
            app=self.app,
        )

    def resize(self, width: int, height: int, *, settle_ms: int = 40) -> None:
        """Resize the root widget and let layouts settle."""
        self.root.resize(width, height)
        if settle_ms > 0:
            self.pump(settle_ms)

    def find(self, selector: str) -> QtWidgets.QWidget | None:
        """Resolve a widget selector within `self.root`."""
        return find_widget(self.root, selector)

    def capture(
        self,
        path: str | os.PathLike[str] | None = None,
        *,
        target: str = "window",
        scenario: str = "",
        widget: QtWidgets.QWidget | None = None,
    ) -> CaptureInfo:
        """Capture `target` (or explicit `widget`) to `path` (or inside `out_dir`)."""
        resolved = widget if widget is not None else self.find(target)
        if resolved is None:
            raise LookupError(
                f"Target widget {target!r} not found under {type(self.root).__name__}"
            )
        if path is None:
            if self.out_dir is None:
                raise ValueError(
                    "Either `path` or `UIInspector(..., out_dir=...)` must be provided"
                )
            stem = f"{scenario}_{target}" if scenario else target
            out_path = self.out_dir / f"{stem}.png"
        else:
            out_path = pathlib.Path(path)
            if not out_path.is_absolute() and self.out_dir is not None:
                out_path = self.out_dir / out_path
        info = capture(resolved, out_path, scenario=scenario, target=target)
        self.captures.append(info)
        return info

    def capture_targets(
        self,
        targets: Iterable[str],
        *,
        scenario: str = "",
        out_dir: str | os.PathLike[str] | None = None,
        strict: bool = False,
    ) -> list[CaptureInfo]:
        """Capture multiple named targets, returning their `CaptureInfo` records."""
        base = pathlib.Path(out_dir) if out_dir is not None else self.out_dir
        if base is None:
            raise ValueError(
                "Either `out_dir` or `UIInspector(..., out_dir=...)` must be provided"
            )
        unique_targets = list(dict.fromkeys(targets))
        single = len(unique_targets) == 1
        results: list[CaptureInfo] = []
        for target in unique_targets:
            widget = self.find(target)
            if widget is None:
                if strict:
                    raise LookupError(
                        f"Target widget {target!r} not found under "
                        f"{type(self.root).__name__}"
                    )
                continue
            if scenario:
                fname = f"{scenario}.png" if single else f"{scenario}_{target}.png"
            else:
                fname = f"{target}.png"
            info = capture(widget, base / fname, scenario=scenario, target=target)
            self.captures.append(info)
            results.append(info)
        return results

    def tree(
        self,
        *,
        target: str | None = None,
        max_depth: int = 8,
    ) -> tuple[list[str], list[LayoutWarning]]:
        """Inspect the widget tree of `root` (or `target`)."""
        widget = self.root if target is None else self.find(target)
        if widget is None:
            raise LookupError(
                f"Target widget {target!r} not found under {type(self.root).__name__}"
            )
        return inspect_tree(
            widget,
            max_depth=max_depth,
            ignore_zero_size=self.ignore_zero_size,
        )

    def warnings(
        self,
        *,
        target: str | None = None,
        max_depth: int = 8,
        record: bool = False,
    ) -> list[LayoutWarning]:
        """Return layout warnings for `root` (or `target`)."""
        _, warns = self.tree(target=target, max_depth=max_depth)
        if record:
            self.collected_warnings.extend(warns)
        return warns

    def write_manifest(
        self,
        path: str | os.PathLike[str] | None = None,
        *,
        extra: Mapping[str, Any] | None = None,
        warnings: Iterable[LayoutWarning] | None = None,
    ) -> pathlib.Path:
        """Write a JSON manifest of captures and layout warnings."""
        if path is None:
            if self.out_dir is None:
                raise ValueError(
                    "Either `path` or `UIInspector(..., out_dir=...)` must be provided"
                )
            out_path = self.out_dir / "manifest.json"
        else:
            out_path = pathlib.Path(path)
        out_path.parent.mkdir(parents=True, exist_ok=True)
        warn_list = (
            list(warnings) if warnings is not None else list(self.collected_warnings)
        )
        payload: dict[str, Any] = {
            "size": f"{self.root.width()}x{self.root.height()}",
            "captures": [asdict(c) for c in self.captures],
            "warnings": [asdict(w) for w in warn_list],
        }
        if extra:
            payload.update(extra)
        out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
        return out_path

capture(path: str | os.PathLike[str] | None = None, *, target: str = 'window', scenario: str = '', widget: QtWidgets.QWidget | None = None) -> CaptureInfo

Capture target (or explicit widget) to path (or inside out_dir).

Source code in prettyqt/debugging/inspector.py
def capture(
    self,
    path: str | os.PathLike[str] | None = None,
    *,
    target: str = "window",
    scenario: str = "",
    widget: QtWidgets.QWidget | None = None,
) -> CaptureInfo:
    """Capture `target` (or explicit `widget`) to `path` (or inside `out_dir`)."""
    resolved = widget if widget is not None else self.find(target)
    if resolved is None:
        raise LookupError(
            f"Target widget {target!r} not found under {type(self.root).__name__}"
        )
    if path is None:
        if self.out_dir is None:
            raise ValueError(
                "Either `path` or `UIInspector(..., out_dir=...)` must be provided"
            )
        stem = f"{scenario}_{target}" if scenario else target
        out_path = self.out_dir / f"{stem}.png"
    else:
        out_path = pathlib.Path(path)
        if not out_path.is_absolute() and self.out_dir is not None:
            out_path = self.out_dir / out_path
    info = capture(resolved, out_path, scenario=scenario, target=target)
    self.captures.append(info)
    return info

capture_targets(targets: Iterable[str], *, scenario: str = '', out_dir: str | os.PathLike[str] | None = None, strict: bool = False) -> list[CaptureInfo]

Capture multiple named targets, returning their CaptureInfo records.

Source code in prettyqt/debugging/inspector.py
def capture_targets(
    self,
    targets: Iterable[str],
    *,
    scenario: str = "",
    out_dir: str | os.PathLike[str] | None = None,
    strict: bool = False,
) -> list[CaptureInfo]:
    """Capture multiple named targets, returning their `CaptureInfo` records."""
    base = pathlib.Path(out_dir) if out_dir is not None else self.out_dir
    if base is None:
        raise ValueError(
            "Either `out_dir` or `UIInspector(..., out_dir=...)` must be provided"
        )
    unique_targets = list(dict.fromkeys(targets))
    single = len(unique_targets) == 1
    results: list[CaptureInfo] = []
    for target in unique_targets:
        widget = self.find(target)
        if widget is None:
            if strict:
                raise LookupError(
                    f"Target widget {target!r} not found under "
                    f"{type(self.root).__name__}"
                )
            continue
        if scenario:
            fname = f"{scenario}.png" if single else f"{scenario}_{target}.png"
        else:
            fname = f"{target}.png"
        info = capture(widget, base / fname, scenario=scenario, target=target)
        self.captures.append(info)
        results.append(info)
    return results

find(selector: str) -> QtWidgets.QWidget | None

Resolve a widget selector within self.root.

Source code in prettyqt/debugging/inspector.py
def find(self, selector: str) -> QtWidgets.QWidget | None:
    """Resolve a widget selector within `self.root`."""
    return find_widget(self.root, selector)

pump(ms: int = 40) -> None

Process Qt events for ms milliseconds.

Source code in prettyqt/debugging/inspector.py
def pump(self, ms: int = 40) -> None:
    """Process Qt events for `ms` milliseconds."""
    pump(self.app, ms=ms)

resize(width: int, height: int, *, settle_ms: int = 40) -> None

Resize the root widget and let layouts settle.

Source code in prettyqt/debugging/inspector.py
def resize(self, width: int, height: int, *, settle_ms: int = 40) -> None:
    """Resize the root widget and let layouts settle."""
    self.root.resize(width, height)
    if settle_ms > 0:
        self.pump(settle_ms)

tree(*, target: str | None = None, max_depth: int = 8) -> tuple[list[str], list[LayoutWarning]]

Inspect the widget tree of root (or target).

Source code in prettyqt/debugging/inspector.py
def tree(
    self,
    *,
    target: str | None = None,
    max_depth: int = 8,
) -> tuple[list[str], list[LayoutWarning]]:
    """Inspect the widget tree of `root` (or `target`)."""
    widget = self.root if target is None else self.find(target)
    if widget is None:
        raise LookupError(
            f"Target widget {target!r} not found under {type(self.root).__name__}"
        )
    return inspect_tree(
        widget,
        max_depth=max_depth,
        ignore_zero_size=self.ignore_zero_size,
    )

wait_until(predicate: Callable[[], object], *, timeout_ms: int = 5000, interval_ms: int = 10) -> bool

Process Qt events until predicate() returns truthy or times out.

Source code in prettyqt/debugging/inspector.py
def wait_until(
    self,
    predicate: Callable[[], object],
    *,
    timeout_ms: int = 5000,
    interval_ms: int = 10,
) -> bool:
    """Process Qt events until `predicate()` returns truthy or times out."""
    return wait_until(
        predicate,
        timeout_ms=timeout_ms,
        interval_ms=interval_ms,
        app=self.app,
    )

warnings(*, target: str | None = None, max_depth: int = 8, record: bool = False) -> list[LayoutWarning]

Return layout warnings for root (or target).

Source code in prettyqt/debugging/inspector.py
def warnings(
    self,
    *,
    target: str | None = None,
    max_depth: int = 8,
    record: bool = False,
) -> list[LayoutWarning]:
    """Return layout warnings for `root` (or `target`)."""
    _, warns = self.tree(target=target, max_depth=max_depth)
    if record:
        self.collected_warnings.extend(warns)
    return warns

write_manifest(path: str | os.PathLike[str] | None = None, *, extra: Mapping[str, Any] | None = None, warnings: Iterable[LayoutWarning] | None = None) -> pathlib.Path

Write a JSON manifest of captures and layout warnings.

Source code in prettyqt/debugging/inspector.py
def write_manifest(
    self,
    path: str | os.PathLike[str] | None = None,
    *,
    extra: Mapping[str, Any] | None = None,
    warnings: Iterable[LayoutWarning] | None = None,
) -> pathlib.Path:
    """Write a JSON manifest of captures and layout warnings."""
    if path is None:
        if self.out_dir is None:
            raise ValueError(
                "Either `path` or `UIInspector(..., out_dir=...)` must be provided"
            )
        out_path = self.out_dir / "manifest.json"
    else:
        out_path = pathlib.Path(path)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    warn_list = (
        list(warnings) if warnings is not None else list(self.collected_warnings)
    )
    payload: dict[str, Any] = {
        "size": f"{self.root.width()}x{self.root.height()}",
        "captures": [asdict(c) for c in self.captures],
        "warnings": [asdict(w) for w in warn_list],
    }
    if extra:
        payload.update(extra)
    out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    return out_path

:fa-brands-github: Show source on GitHub