Skip to content

debugging

Class info

Classes

Name Children Inherits
CaptureInfo
prettyqt.debugging.inspector
Metadata for a captured widget screenshot.
    ErrorMessageBox
    prettyqt.debugging.errormessagebox
    An message box widget for displaying Python exception.
      LayoutWarning
      prettyqt.debugging.inspector
      A layout diagnostic emitted while inspecting a widget tree.
        MessageHandler
        prettyqt.debugging.messagehandler
          ProxyComparerWidget
          prettyqt.debugging.proxycomparerwidget
          Splitter widget showing a comparison view between a proxy and its sourceModels.
            QObjectDetailsDialog
            prettyqt.debugging.qobjectdetailsdialog
            A dialog containing information about a QObject.
              Stalker
              prettyqt.debugging.stalker
                TracebackDialog
                prettyqt.debugging.tracebackdialog
                A dialog box that shows Python traceback.
                  UIInspector
                  prettyqt.debugging.inspector
                  High-level inspection and screenshot helper bound to a root widget.

                    🛈 DocStrings

                    CaptureInfo dataclass

                    Metadata for a captured widget screenshot.

                    Source code in prettyqt/debugging/inspector.py
                    @dataclass(frozen=True, slots=True)
                    class CaptureInfo:
                        """Metadata for a captured widget screenshot."""
                    
                        scenario: str
                        target: str
                        path: str
                        width: int
                        height: int
                    

                    ErrorMessageBox

                    Bases: MessageBox

                    An message box widget for displaying Python exception.

                    Source code in prettyqt/debugging/errormessagebox.py
                    class ErrorMessageBox(widgets.MessageBox):
                        """An message box widget for displaying Python exception."""
                    
                        def __init__(self, title: str, text_or_exception: str | Exception, parent=None):
                            if isinstance(text_or_exception, str):
                                text = text_or_exception
                                exc = None
                            else:
                                text = str(text_or_exception)
                                exc = text_or_exception
                            super().__init__(
                                # icon=MBox.Icon.Critical,
                                window_title=title,
                                text=str(text)[:1000],
                                buttons=["ok", "help", "close"],
                                parent=parent,
                            )
                    
                            self._exc = exc
                    
                            traceback_button = self.get_button("help")
                            traceback_button.setText("Show traceback")
                            close_button = self.get_button("close")
                            close_button.setText("Quit application")
                    
                        def exec(self):
                            match super().exec():
                                case widgets.MessageBox.StandardButton.Help:
                                    tb = self._get_traceback()
                                    dlg = debugging.TracebackDialog(self)
                                    dlg.setText(tb)
                                    dlg.exec()
                                    return None
                                case widgets.MessageBox.StandardButton.Close:
                                    sys.exit(1)
                                case widgets.MessageBox.StandardButton.Ok:
                                    return True
                    
                        # @classmethod
                        # def setup_example(cls):
                        #     return cls("Title", "Test message")
                    
                        @classmethod
                        def from_exc(cls, e: Exception, parent=None):
                            """Construct message box from a exception."""
                            return cls(type(e).__name__, e, parent)
                    
                        @classmethod
                        def raise_(cls, e: Exception, parent=None):
                            """Raise exception in the message box."""
                            # unwrap EmitLoopError
                            return cls.from_exc(e, parent=parent).exec()
                    
                        def _get_traceback(self):
                            if self._exc is None:
                                return traceback.format_exc()
                            formatter = get_tb_formatter(gui.Font.mono().family())
                            return formatter(self._exc, as_html=True)
                    
                        @classmethod
                        def _excepthook(cls, exc_type: type[Exception], exc_value: Exception, exc_traceback):
                            """Exception hook used during application execution."""
                            strings = traceback.format_exception(exc_type, exc_value, exc_traceback)
                            tb = "".join(strings)
                            logger.error(tb)
                            return ErrorMessageBox.raise_(exc_value, parent=None)
                    

                    from_exc(e: Exception, parent=None) classmethod

                    Construct message box from a exception.

                    Source code in prettyqt/debugging/errormessagebox.py
                    @classmethod
                    def from_exc(cls, e: Exception, parent=None):
                        """Construct message box from a exception."""
                        return cls(type(e).__name__, e, parent)
                    

                    raise_(e: Exception, parent=None) classmethod

                    Raise exception in the message box.

                    Source code in prettyqt/debugging/errormessagebox.py
                    @classmethod
                    def raise_(cls, e: Exception, parent=None):
                        """Raise exception in the message box."""
                        # unwrap EmitLoopError
                        return cls.from_exc(e, parent=parent).exec()
                    

                    LayoutWarning dataclass

                    A layout diagnostic emitted while inspecting a widget tree.

                    Source code in prettyqt/debugging/inspector.py
                    @dataclass(frozen=True, slots=True)
                    class LayoutWarning:
                        """A layout diagnostic emitted while inspecting a widget tree."""
                    
                        widget: str
                        kind: str
                        detail: str
                    

                    ProxyComparerWidget

                    Bases: Splitter

                    Splitter widget showing a comparison view between a proxy and its sourceModels.

                    ![Image title](../../images/proxycomparerwidget.png)
                    ProxyComparerWidget
                    Source code in prettyqt/debugging/proxycomparerwidget.py
                    class ProxyComparerWidget(widgets.Splitter):
                        """Splitter widget showing a comparison view between a proxy and its sourceModels.
                    
                        <figure markdown>
                          ![Image title](../../images/proxycomparerwidget.png)
                          <figcaption>ProxyComparerWidget</figcaption>
                        </figure>
                        """
                    
                        def __init__(
                            self,
                            model: core.QAbstractItemModel,
                            itemview: (
                                Literal["tree", "table", "list"] | type[widgets.QAbstractItemView]
                            ) = "table",
                            delegate: (
                                widgets.abstractitemview.DelegateStr | widgets.QItemDelegate | None
                            ) = "editor",
                            link_selections: bool = True,
                            **kwargs,
                        ):
                            super().__init__(**kwargs)
                            self.model_itemviews = []
                            self.linker = None
                            # determine ItemView class for the models
                            match itemview:
                                case "tree":
                                    view_cls = widgets.TreeView
                                case "table":
                                    view_cls = widgets.TableView
                                case "list":
                                    view_cls = widgets.ListView
                                case type():
                                    view_cls = cast("type[widgets.AbstractItemViewMixin]", itemview)
                                case _:
                                    raise TypeError(itemview)
                    
                            # collect models
                            models = []
                            while isinstance(model, core.QAbstractProxyModel):
                                models.append(model)
                                model = model.sourceModel()
                            models.append(model)
                    
                            # add column for each model
                    
                            for model in reversed(models):
                                container = widgets.Widget()
                                layout = container.set_layout("vertical")
                                table = view_cls()
                                table.set_model(model)
                                table.set_delegate(delegate)
                                self.model_itemviews.append(table)
                                prop_table = custom_widgets.QObjectPropertiesTableView()
                                prop_table.set_qobject(model)
                                header = widgets.Label(type(model).__name__)
                                layout.add(header)
                                col_splitter = widgets.Splitter("vertical")
                                col_splitter.add(table)
                                col_splitter.add(prop_table)
                                layout.add(col_splitter)
                                self.add(container)
                            if link_selections:
                                self.linker = itemmodels.LinkedSelectionModel(*self.model_itemviews)
                    

                    QObjectDetailsDialog

                    Bases: MainWindow

                    A dialog containing information about a QObject.

                    Source code in prettyqt/debugging/qobjectdetailsdialog.py
                    class QObjectDetailsDialog(widgets.MainWindow):
                        """A dialog containing information about a QObject."""
                    
                        def __init__(
                            self,
                            qobject: core.QObject,
                            *args,
                            object_name="qobject_details_dialog",
                            **kwargs,
                        ):
                            from prettyqt import ipython
                    
                            super().__init__(*args, object_name=object_name, **kwargs)
                            self.qobject = qobject
                            self.console = ipython.InProcessIPythonWidget(self)
                            self.console.push_vars(dict(app=widgets.app(), qobject=qobject))
                            self.tabwidget, self.propertyview = get_tabbed(qobject)
                            self.hierarchyview = custom_widgets.QObjectHierarchyTreeView()
                            self.hierarchyview.set_qobject(qobject)
                            sel_model = self.hierarchyview.selectionModel()
                            sel_model.currentRowChanged.connect(self._current_changed)
                            self.logtable = custom_widgets.LogRecordTableView()
                            self.logtable.set_logger(logging.getLogger())
                            w = widgets.Widget()
                            w.set_layout("vertical")
                            self.stalkers = []
                            stalker = debugging.Stalker(qobject, log_level=logging.DEBUG)
                            stalker.hook()
                            self.stalkers.append(stalker)
                            for widget in qobject.findChildren(widgets.QWidget):
                                stalker = debugging.Stalker(widget, log_level=logging.DEBUG)
                                stalker.hook()
                                fn = functools.partial(self._on_widget_click, widget)
                                stalker.leftclick_detected.connect(fn)
                                self.stalkers.append(stalker)
                            # mdi_area = widgets.GraphicsView()
                            # subwindow = widgets.GraphicsProxyWidget ()
                            # # mdi_area.installEventFilter(self)
                            # # subwindow.installEventFilter(self)
                            # subwindow.set_widget(qobject)
                            # mdi_area.scene().add(subwindow)
                            widget = widgets.Widget()
                            layout = widget.set_layout("horizontal")
                            if isinstance(qobject, widgets.QWidget):
                                layout.add(qobject)
                            self.setCentralWidget(widget)
                            # qobject.position_on(widget)
                    
                            self.add_dockwidget(self.hierarchyview, window_title="Hierarchy view")
                            self.add_dockwidget(self.tabwidget, window_title="Property view")
                            self.add_dockwidget(self.logtable, window_title="Log", visible=False)
                            self.add_dockwidget(self.console, window_title="Console", visible=False)
                            self.menubar = self.menuBar()
                            action = widgets.mainwindow.PopupMenuAction("Docks", parent=self)
                            self.menubar.addAction(action)
                            self.position_on("screen", scale_ratio=0.8)
                    
                        @classmethod
                        def setup_example(cls):
                            return None
                    
                        def closeEvent(self, event):
                            for stalker in self.stalkers:
                                stalker.unhook()
                            super().closeEvent(event)
                    
                        def _current_changed(self, new, old):
                            # logger.info(f"{new=} {old=}")
                            role = itemmodels.widgethierarchymodel.BaseHierarchyModel.Roles.WidgetRole
                            if (qobject := self.hierarchyview.current_data(role)) is not None:
                                self.propertyview.set_qobject(qobject)
                    
                        def _on_widget_click(self, widget):
                            logger.info(repr(widget))
                            self.hierarchyview.select_object(widget)
                    

                    Stalker

                    Bases: Object

                    Source code in prettyqt/debugging/stalker.py
                    class Stalker(core.Object):
                        # @core.Enum
                        # class LogLevel(enum.IntEnum):
                        #     """Log level."""
                    
                        #     DEBUG = logging.DEBUG
                        #     INFO = logging.INFO
                        #     WARNING = logging.WARNING
                        #     CRITICAL = logging.CRITICAL
                        #     ERROR = logging.ERROR
                    
                        keypress_detected = core.Signal(str)
                        leftclick_detected = core.Signal(core.QPointF)
                        rightclick_detected = core.Signal(core.QPointF)
                        event_detected = core.Signal(core.QEvent)
                        signal_emitted = core.Signal(core.MetaMethod, object)  # signal, args
                        signal_connected = core.Signal(core.MetaMethod)
                        signal_disconnected = core.Signal(core.MetaMethod)
                    
                        def __init__(
                            self,
                            qobject: core.QObject,
                            include: core.event.TypeStr | list[core.event.TypeStr] | None = None,
                            exclude: core.event.TypeStr | list[core.event.TypeStr] | None = None,
                            **kwargs: Any,
                        ):
                            self._log_level = logging.INFO
                            super().__init__(**kwargs)
                            self._obj = qobject
                            qmeta = self._obj.metaObject()
                            assert qmeta
                            self._meta = core.MetaObject(qmeta)
                            self.counter: collections.defaultdict[str, int] = collections.defaultdict(int)
                            self.signal_counter: collections.defaultdict[str, int] = collections.defaultdict(
                                int
                            )
                            self.exclude: core.event.TypeStr | list[core.event.TypeStr] = (
                                ["meta_call", "timer"] if exclude is None else exclude
                            )
                            self.include = include
                            self._handles: list[core.QMetaObject.Connection] = []
                            self.eventcatcher: eventfilters.EventCatcher | None = None
                    
                        def __enter__(self):
                            self.hook()
                            return self
                    
                        def __exit__(self, typ, value, traceback):
                            self.unhook()
                    
                        @property
                        def eventsignals(self):
                            # needs a prettyqt object (add_callback_for_event)
                            return EventSignaller(cast("core.ObjectMixin", self._obj))
                    
                        def hook(self):
                            # enable event logging by installing EventCatcher, which includes logging
                            self.eventcatcher = eventfilters.EventCatcher(
                                self.include, self.exclude, self._on_event_detected, parent=self._obj
                            )
                            self._obj.installEventFilter(self.eventcatcher)
                            # enable logging of signals emitted by connecting all signals to our fn
                            for signal in self._meta.get_signals(only_notifiers=False):
                                signal_name = signal.get_name()
                                # PyQt reports non-existing signals in MetaObject.
                                if not hasattr(self._obj, signal_name):
                                    continue
                                signal_instance = getattr(self._obj, signal_name)
                                fn = self._on_signal_emitted(signal)
                                handle = signal_instance.connect(fn)
                                self._handles.append(handle)
                            self.log(f"Stalking {len(self._handles)} signals")
                            # enable logging of all signal (dis)connections by hooking to connectNotify
                            self.old_connectNotify = self._obj.connectNotify
                            self.old_disconnectNotify = self._obj.disconnectNotify
                            self._obj.connectNotify = self._on_signal_connected
                            self._obj.disconnectNotify = self._on_signal_disconnected
                            # self._obj.destroyed.connect(self.unhook)
                            # self.destroyed.connect(self.unhook)
                    
                        def unhook(self):
                            if self.eventcatcher is None:
                                logger.warning("unhook() called before hook()")
                                return
                            """Clean up our mess."""
                            self._obj.connectNotify = self.old_connectNotify  # ty: ignore[invalid-assignment]
                            self._obj.disconnectNotify = self.old_disconnectNotify  # ty: ignore[invalid-assignment]
                            self.old_connectNotify = None
                            self.old_disconnectNotify = None
                            for handle in self._handles:
                                self._obj.disconnect(handle)  # ty: ignore[invalid-argument-type]  # a Connection
                            self._handles = []
                            with contextlib.suppress(RuntimeError):
                                self._obj.removeEventFilter(self.eventcatcher)
                    
                        def log(self, message: str):
                            if self.log_level:
                                with contextlib.suppress(RuntimeError):
                                    logger.log(self._log_level, f"{self._obj!r}: {message}")  # noqa: G004
                    
                        def _on_signal_connected(self, qsignal: core.QMetaMethod):
                            signal = core.MetaMethod(qsignal)
                            self.log(f"Connected signal {signal.get_name()}")
                            self.signal_connected.emit(signal)
                    
                        def _on_signal_disconnected(self, qsignal: core.QMetaMethod):
                            signal = core.MetaMethod(qsignal)
                            self.log(f"Disconnected signal {signal.get_name()}")
                            self.signal_disconnected.emit(signal)
                    
                        def _on_event_detected(self, event) -> bool:
                            """Used for EventCatcher, returns false to not eat signals."""
                            try:
                                self.event_detected.emit(event)
                            except RuntimeError:
                                return False
                            match event.type():
                                case core.Event.Type.KeyPress:
                                    combo = gui.KeySequence(event.keyCombination()).toString()
                                    self.keypress_detected.emit(combo)
                                case core.Event.Type.MouseButtonRelease:
                                    if event.button() == constants.MouseButton.LeftButton:
                                        self.leftclick_detected.emit(event.position())
                                    if event.button() == constants.MouseButton.RightButton:
                                        self.rightclick_detected.emit(event.position())
                            self.log(f"Received event {event.type()!r}")
                            self.counter[event.type()] += 1
                            return False
                    
                        def _on_signal_emitted(self, signal: core.MetaMethod):
                            def fn(*args, **kwargs):
                                try:
                                    self.signal_emitted.emit(signal, args)
                                    self.signal_counter[signal.get_name()] += 1
                                    self.log(f"Emitted signal {signal.get_name()}{args}")
                                except RuntimeError:
                                    pass
                    
                            return fn
                    
                        def set_log_level(self, level: int):
                            self._log_level = level
                    
                        def get_log_level(self) -> int:
                            return self._log_level
                    
                        def count_children(
                            self,
                            type_filter: type[T] = core.QObject,  # ty: ignore[invalid-parameter-default]
                        ) -> collections.Counter:
                            objects = self._obj.findChildren(type_filter)
                            return collections.Counter([type(o) for o in objects])
                    
                        def show(self):
                            from prettyqt import custom_widgets
                    
                            widget = custom_widgets.LogRecordTableView()
                            widget.set_logger(logger, level=self.log_level)
                            widget.show()
                    
                        log_level = core.Property(
                            int,
                            get_log_level,
                            set_log_level,
                            doc="Level to use for logging",
                        )
                    

                    TracebackDialog

                    Bases: Dialog

                    A dialog box that shows Python traceback.

                    Source code in prettyqt/debugging/tracebackdialog.py
                    class TracebackDialog(widgets.Dialog):
                        """A dialog box that shows Python traceback."""
                    
                        def __init__(self, parent: widgets.QWidget | None = None):
                            super().__init__(parent, window_title="Traceback")
                            layout = self.set_layout("vertical")
                            self._text = widgets.TextEdit(self, read_only=True, line_wrap_mode="none")
                            self._text.setFontFamily(gui.Font.mono().family())
                            layout.addWidget(self._text)
                            self.resize(600, 400)
                    
                        def setText(self, text: str):
                            """Always set text as a HTML text."""
                            self._text.setHtml(text)
                    

                    setText(text: str)

                    Always set text as a HTML text.

                    Source code in prettyqt/debugging/tracebackdialog.py
                    def setText(self, text: str):
                        """Always set text as a HTML text."""
                        self._text.setHtml(text)
                    

                    UIInspector

                    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
                    

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

                    Grab a screenshot of widget and save it to path.

                    Source code in prettyqt/debugging/inspector.py
                    def capture(
                        widget: QtWidgets.QWidget,
                        path: str | os.PathLike[str],
                        *,
                        scenario: str = "",
                        target: str = "",
                    ) -> CaptureInfo:
                        """Grab a screenshot of `widget` and save it to `path`."""
                        out_path = pathlib.Path(path)
                        out_path.parent.mkdir(parents=True, exist_ok=True)
                        pixmap = widget.grab()
                        pixmap.save(str(out_path))
                        return CaptureInfo(
                            scenario=scenario,
                            target=target,
                            path=str(out_path),
                            width=pixmap.width(),
                            height=pixmap.height(),
                        )
                    

                    default_ignore_zero_size(widget: QtWidgets.QWidget) -> bool

                    Return True for internal Qt widgets that legitimately have zero size.

                    Source code in prettyqt/debugging/inspector.py
                    def default_ignore_zero_size(widget: QtWidgets.QWidget) -> bool:
                        """Return True for internal Qt widgets that legitimately have zero size."""
                        if (
                            type(widget).__name__ in _DEFAULT_ZERO_SIZE_CLASSES
                            or widget.objectName() in _DEFAULT_ZERO_SIZE_NAMES
                        ):
                            return True
                        return isinstance(widget, QtWidgets.QMenuBar) and not widget.actions()
                    

                    ensure_offscreen() -> None

                    Configure Qt to use the offscreen platform plugin if unset.

                    Source code in prettyqt/debugging/inspector.py
                    def ensure_offscreen() -> None:
                        """Configure Qt to use the offscreen platform plugin if unset."""
                        os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
                    

                    find_widget(root: QtWidgets.QWidget, selector: str) -> QtWidgets.QWidget | None

                    Resolve a widget selector within root.

                    Resolves "window" / "root" (or root.objectName()) to root, then checks QDockWidget children by objectName, and finally falls back to root.findChild(QWidget, selector).

                    Source code in prettyqt/debugging/inspector.py
                    def find_widget(
                        root: QtWidgets.QWidget,
                        selector: str,
                    ) -> QtWidgets.QWidget | None:
                        """Resolve a widget selector within `root`.
                    
                        Resolves `"window"` / `"root"` (or `root.objectName()`) to `root`,
                        then checks `QDockWidget` children by `objectName`, and finally falls
                        back to `root.findChild(QWidget, selector)`.
                        """
                        if selector in ("window", "root") or (selector and selector == root.objectName()):
                            return root
                        for dock in root.findChildren(QtWidgets.QDockWidget):
                            if dock.objectName() == selector:
                                return dock
                        return root.findChild(QtWidgets.QWidget, selector)
                    

                    inspect_tree(root: QtWidgets.QWidget, *, max_depth: int = 8, ignore_zero_size: Callable[[QtWidgets.QWidget], bool] | None = None) -> tuple[list[str], list[LayoutWarning]]

                    Return an indented widget tree and layout diagnostics for root.

                    Checks for: - clipped-label: visible non-wrapping QLabel whose rendered text exceeds width - cramped-button: visible QAbstractButton narrower than its sizeHint() - zero-size: visible widget with 0 width or height - out-of-bounds: visible child / SubWindow extending outside its parent's rect

                    Source code in prettyqt/debugging/inspector.py
                    def inspect_tree(
                        root: QtWidgets.QWidget,
                        *,
                        max_depth: int = 8,
                        ignore_zero_size: Callable[[QtWidgets.QWidget], bool] | None = None,
                    ) -> tuple[list[str], list[LayoutWarning]]:
                        """Return an indented widget tree and layout diagnostics for `root`.
                    
                        Checks for:
                        - `clipped-label`: visible non-wrapping `QLabel` whose rendered text exceeds width
                        - `cramped-button`: visible `QAbstractButton` narrower than its `sizeHint()`
                        - `zero-size`: visible widget with 0 width or height
                        - `out-of-bounds`: visible child / `SubWindow` extending outside its parent's rect
                        """
                        ignore_zero = (
                            ignore_zero_size if ignore_zero_size is not None else default_ignore_zero_size
                        )
                        lines: list[str] = []
                        warnings: list[LayoutWarning] = []
                    
                        def visit(widget: QtWidgets.QWidget, depth: int) -> None:
                            if depth > max_depth or not widget.isVisible():
                                return
                            if widget is not root and _is_offscreen_dock(widget):
                                return
                            geo = widget.geometry()
                            label = _label_for(widget)
                            extra = ""
                            if isinstance(widget, QtWidgets.QLabel):
                                plain, needed = _label_text_metrics(widget)
                                preview = plain.replace("\n", " ")[:LABEL_PREVIEW_LEN]
                                if preview:
                                    extra = f' text="{preview}"'
                                if (
                                    plain
                                    and not widget.wordWrap()
                                    and widget.width() > 0
                                    and needed > widget.width() + CLIP_TOLERANCE_PX
                                ):
                                    warnings.append(
                                        LayoutWarning(
                                            label,
                                            "clipped-label",
                                            f'"{preview}" needs {needed}px, has {widget.width()}px',
                                        )
                                    )
                            elif isinstance(widget, QtWidgets.QAbstractButton):
                                preview = widget.text().replace("&", "")[:BUTTON_PREVIEW_LEN]
                                if preview:
                                    extra = f' text="{preview}"'
                                    needed = widget.sizeHint().width()
                                    if 0 < widget.width() < needed - CLIP_TOLERANCE_PX:
                                        warnings.append(
                                            LayoutWarning(
                                                label,
                                                "cramped-button",
                                                f'"{preview}" sizeHint={needed}px, width={widget.width()}px',
                                            )
                                        )
                            elif isinstance(widget, QtWidgets.QDockWidget):
                                extra = f' title="{widget.windowTitle()}"'
                    
                            if (widget.width() == 0 or widget.height() == 0) and not ignore_zero(widget):
                                warnings.append(
                                    LayoutWarning(
                                        label,
                                        "zero-size",
                                        f"visible widget has geometry {geo.width()}x{geo.height()}",
                                    )
                                )
                    
                            if (oob := _check_out_of_bounds(widget, root)) is not None:
                                warnings.append(oob)
                    
                            indent = "  " * depth
                            lines.append(
                                f"{indent}{label} [{geo.x()},{geo.y()} {geo.width()}x{geo.height()}]{extra}"
                            )
                            for child in widget.children():
                                if isinstance(child, QtWidgets.QWidget):
                                    visit(child, depth + 1)
                    
                        visit(root, 0)
                        return lines, warnings
                    

                    pump(app: QtCore.QCoreApplication | None = None, ms: int = 40) -> None

                    Process Qt events for ms milliseconds so layouts and timers settle.

                    Source code in prettyqt/debugging/inspector.py
                    def pump(
                        app: QtCore.QCoreApplication | None = None,
                        ms: int = 40,
                    ) -> None:
                        """Process Qt events for `ms` milliseconds so layouts and timers settle."""
                        qapp = app if app is not None else QtCore.QCoreApplication.instance()
                        if qapp is None:
                            return
                        flags = QtCore.QEventLoop.ProcessEventsFlag.AllEvents
                        deadline = time.monotonic() + ms / 1000.0
                        while time.monotonic() < deadline:
                            qapp.processEvents(flags, 10)
                            time.sleep(0.005)
                        qapp.processEvents(flags)
                    

                    wait_until(predicate: Callable[[], object], *, timeout_ms: int = 5000, interval_ms: int = 10, app: QtCore.QCoreApplication | None = None) -> bool

                    Process Qt events until predicate() returns truthy or timeout_ms elapses.

                    Source code in prettyqt/debugging/inspector.py
                    def wait_until(
                        predicate: Callable[[], object],
                        *,
                        timeout_ms: int = 5000,
                        interval_ms: int = 10,
                        app: QtCore.QCoreApplication | None = None,
                    ) -> bool:
                        """Process Qt events until `predicate()` returns truthy or `timeout_ms` elapses."""
                        qapp = app if app is not None else QtCore.QCoreApplication.instance()
                        flags = QtCore.QEventLoop.ProcessEventsFlag.AllEvents
                        deadline = time.monotonic() + timeout_ms / 1000.0
                        step_s = max(interval_ms, 1) / 1000.0
                        while True:
                            if qapp is not None:
                                qapp.processEvents(flags, interval_ms)
                            if predicate():
                                return True
                            remaining = deadline - time.monotonic()
                            if remaining <= 0:
                                return False
                            time.sleep(min(step_s, remaining))