Skip to content

prettyqtmarkdown

Class info

Classes

Name Children Inherits
MarkdownWidget
prettyqt.prettyqtmarkdown.markdownwidget
A widget used for displaying a preview of a generated mknodes tree.
    MkItemModelTable
    prettyqt.prettyqtmarkdown.mkitemmodeltable
    Table which can display Qt ItemModels.
      MkNodesModel
      prettyqt.prettyqtmarkdown.markdownmodel
      An ItemModel for displaying a mknodes tree.
        MkPrettyQtDiagram
        prettyqt.prettyqtmarkdown.mkprettyqtdiagram
          MkPropertyTable
          prettyqt.prettyqtmarkdown.mkpropertytable
          A table containing info about Qt properties.
            MkWidgetScreenShot
            prettyqt.prettyqtmarkdown.mkwidgetscreenshot
            Node to easily create and embed a widget screenshot into docs.
              QtLinkProvider
              prettyqt.prettyqtmarkdown.qtlinkprovider

                🛈 DocStrings

                Module containing stuff to help buidling docs.

                This module builds on mknodes and contains some new nodes to help building documentation, an MkItemModelTable to easily display Qt ItemModels as Markdown Tables as well as a model + widget to preview a generated mknodes tree.

                MarkdownWidget

                Bases: Widget

                A widget used for displaying a preview of a generated mknodes tree.

                Source code in prettyqt/prettyqtmarkdown/markdownwidget.py
                class MarkdownWidget(widgets.Widget):
                    """A widget used for displaying a preview of a generated mknodes tree."""
                
                    def __init__(self, *args, **kwargs):
                        super().__init__(*args, **kwargs)
                        self.tree = widgets.TreeView()
                        self.textbox = custom_widgets.CodeEditor()
                        self.textbox.set_syntaxhighlighter("markdown")
                        layout = self.set_layout("grid")
                        layout[0, 0] = self.tree
                        layout[0, 1] = self.textbox
                
                    def set_markdown(self, item: mknodes.MkNode):
                        model = prettyqtmarkdown.MkNodesModel(item)
                        self.tree.set_model(model)
                        self.tree.selectionModel().currentRowChanged.connect(self._on_current_change)
                
                    def _on_current_change(self, new, old):
                        if not new.isValid() or new.model() is None:
                            return
                        text = new.data(new.model().Roles.MarkdownRole)
                        self.textbox.set_text(text)
                

                MkItemModelTable

                Bases: MkTable

                Table which can display Qt ItemModels.

                The given ItemModel will get proxied with a ProxyModel which translates data from some of the ItemRoles to Markup styling, and afterwords converted to a Markup table.

                Source code in prettyqt/prettyqtmarkdown/mkitemmodeltable.py
                class MkItemModelTable(mknodes.MkTable):
                    """Table which can display Qt ItemModels.
                
                    The given ItemModel will get proxied with a ProxyModel which translates
                    data from some of the ItemRoles to Markup styling, and afterwords converted
                    to a Markup table.
                    """
                
                    def __init__(
                        self,
                        model: core.AbstractItemModelMixin,
                        use_checkstate_role: bool = True,
                        **kwargs: Any,
                    ):
                        """Constructor.
                
                        Arguments:
                            model: The ItemModel to display.
                            use_checkstate_role: whether to display the CheckStateRole value if available.
                            kwargs: Keyword arguments passed to get_table_data.
                        """
                        proxy = itemmodels.SliceToMarkdownProxyModel(None, source_model=model)
                        data, h_header, _ = proxy.get_table_data(
                            use_checkstate_role=use_checkstate_role, **kwargs
                        )
                        data = list(zip(*data))
                        super().__init__(data, columns=h_header)
                

                __init__(model: core.AbstractItemModelMixin, use_checkstate_role: bool = True, **kwargs: Any)

                Constructor.

                Parameters:

                Name Type Description Default
                model AbstractItemModelMixin

                The ItemModel to display.

                required
                use_checkstate_role bool

                whether to display the CheckStateRole value if available.

                True
                kwargs Any

                Keyword arguments passed to get_table_data.

                {}
                Source code in prettyqt/prettyqtmarkdown/mkitemmodeltable.py
                def __init__(
                    self,
                    model: core.AbstractItemModelMixin,
                    use_checkstate_role: bool = True,
                    **kwargs: Any,
                ):
                    """Constructor.
                
                    Arguments:
                        model: The ItemModel to display.
                        use_checkstate_role: whether to display the CheckStateRole value if available.
                        kwargs: Keyword arguments passed to get_table_data.
                    """
                    proxy = itemmodels.SliceToMarkdownProxyModel(None, source_model=model)
                    data, h_header, _ = proxy.get_table_data(
                        use_checkstate_role=use_checkstate_role, **kwargs
                    )
                    data = list(zip(*data))
                    super().__init__(data, columns=h_header)
                

                MkNodesModel

                Bases: TreeModel

                An ItemModel for displaying a mknodes tree.

                Source code in prettyqt/prettyqtmarkdown/markdownmodel.py
                class MkNodesModel(itemmodels.TreeModel):
                    """An ItemModel for displaying a mknodes tree."""
                
                    HEADER: ClassVar = ["Repr", "Type", "Files"]
                
                    class Roles:
                        MarkdownRole = constants.USER_ROLE + 5325
                
                    def headerData(
                        self,
                        section: int,
                        orientation: constants.Orientation,
                        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
                    ):
                        match orientation, role, section:
                            case constants.HORIZONTAL, constants.DISPLAY_ROLE, _:
                                return self.HEADER[section]
                        return None
                
                    def columnCount(self, index: core.ModelIndex | None = None) -> int:
                        return len(self.HEADER)
                
                    def data(
                        self,
                        index: core.ModelIndex,
                        role: constants.ItemDataRole = constants.DISPLAY_ROLE,
                    ):
                        node = self.data_by_index(index).obj
                        match role, index.column():
                            case constants.DISPLAY_ROLE, 0:
                                match node:
                                    case mknodes.MkNav():
                                        return f"{node.title}/"
                                    case mknodes.MkPage():
                                        return node.path
                                    case _:
                                        return repr(node)
                            # case constants.DISPLAY_ROLE, 1:
                            #     with contextlib.suppress(AttributeError):
                            #         return node._to_markdown().count("\n")
                            case constants.DISPLAY_ROLE, 1:
                                return type(node).__name__
                            case constants.DISPLAY_ROLE, 2:
                                keys = node.get_resources().keys()
                                return ", ".join(keys)
                            case self.Roles.MarkdownRole, _:
                                return node.to_markdown()
                
                    def _fetch_object_children(self, item) -> list[MkNodesModel.TreeItem]:
                        return [self.TreeItem(i) for i in item.obj.children]
                
                    def _has_children(self, item) -> bool:
                        return len(item.obj.children) > 0
                

                MkPropertyTable

                Bases: MkTable

                A table containing info about Qt properties.

                Source code in prettyqt/prettyqtmarkdown/mkpropertytable.py
                class MkPropertyTable(mknodes.MkTable):
                    """A table containing info about Qt properties."""
                
                    def __init__(
                        self,
                        qobject: type[core.QObject],
                        user_prop_name: str | None = None,
                        header: str = "",
                    ):
                        lines = []
                        headers = ["Qt Property", "Type", "Doc"]
                        metaobject = qobject.staticMetaObject  # ty: ignore[missing-attribute]  # not in stubs
                        properties = core.MetaObject(metaobject).get_properties()
                        doc_dict = core.Property.get_doc_dict(qobject)
                        for prop in properties:
                            property_name = f"`{prop.get_name()}`"
                            if prop.get_name() == user_prop_name:
                                property_name += " *(User property)*"
                            # if (flag := prop.get_enumerator()):
                            meta_type = prop.get_meta_type()
                            label = (meta_type.get_name() or "").rstrip("*")
                            doc = doc_dict.get(prop.get_name(), "")
                            # mark = "x" if prop.get_name() == user_prop_name else ""
                            sections = [property_name, f"**{label}**", doc]
                            lines.append(sections)
                        super().__init__(columns=headers, data=list(zip(*lines)), header=header)
                

                MkWidgetScreenShot

                Bases: MkBinaryImage

                Node to easily create and embed a widget screenshot into docs.

                Source code in prettyqt/prettyqtmarkdown/mkwidgetscreenshot.py
                class MkWidgetScreenShot(mknodes.MkBinaryImage):
                    """Node to easily create and embed a widget screenshot into docs."""
                
                    def __init__(
                        self,
                        widget: widgets.QWidget,
                        caption: str = "",
                        path: str | None = None,
                        title: str = "Image title",
                        header: str = "",
                        resize_to: datatypes.SizeType | None = None,
                    ):
                        """Constructor.
                
                        Arguments:
                            widget: Widget to make a screenshot from
                            caption: Image caption
                            path: Image path
                            title: Image title
                            header: Section header
                            resize_to: widget screenshot size
                        """
                        if path is None:
                            path = f"{widget.__class__.__name__}_screenshot.png"
                        logger.info("Screenshot for %s", widget)
                        self.resize_to = resize_to
                        self.widget = widget
                        widget.setAttribute(constants.WidgetAttribute.WA_DontShowOnScreen)
                        widget.show()
                        widget.adjustSize()
                        if self.resize_to is not None:
                            widget.resize(datatypes.to_size(self.resize_to))
                        widgets.app().processEvents()
                        pixmap = widget.grab()
                        widget.hide()
                        widget.deleteLater()
                        widgets.app().processEvents()
                        ba = core.ByteArray()
                        buffer = core.QBuffer(ba)
                        buffer.open(core.QIODeviceBase.OpenModeFlag.WriteOnly)
                        pixmap.save(buffer, "PNG")
                        super().__init__(
                            data=bytes(ba.data()),
                            path=path,
                            header=header,
                            caption=caption,
                            title=title,
                        )
                

                __init__(widget: widgets.QWidget, caption: str = '', path: str | None = None, title: str = 'Image title', header: str = '', resize_to: datatypes.SizeType | None = None)

                Constructor.

                Parameters:

                Name Type Description Default
                widget QWidget

                Widget to make a screenshot from

                required
                caption str

                Image caption

                ''
                path str | None

                Image path

                None
                title str

                Image title

                'Image title'
                header str

                Section header

                ''
                resize_to SizeType | None

                widget screenshot size

                None
                Source code in prettyqt/prettyqtmarkdown/mkwidgetscreenshot.py
                def __init__(
                    self,
                    widget: widgets.QWidget,
                    caption: str = "",
                    path: str | None = None,
                    title: str = "Image title",
                    header: str = "",
                    resize_to: datatypes.SizeType | None = None,
                ):
                    """Constructor.
                
                    Arguments:
                        widget: Widget to make a screenshot from
                        caption: Image caption
                        path: Image path
                        title: Image title
                        header: Section header
                        resize_to: widget screenshot size
                    """
                    if path is None:
                        path = f"{widget.__class__.__name__}_screenshot.png"
                    logger.info("Screenshot for %s", widget)
                    self.resize_to = resize_to
                    self.widget = widget
                    widget.setAttribute(constants.WidgetAttribute.WA_DontShowOnScreen)
                    widget.show()
                    widget.adjustSize()
                    if self.resize_to is not None:
                        widget.resize(datatypes.to_size(self.resize_to))
                    widgets.app().processEvents()
                    pixmap = widget.grab()
                    widget.hide()
                    widget.deleteLater()
                    widgets.app().processEvents()
                    ba = core.ByteArray()
                    buffer = core.QBuffer(ba)
                    buffer.open(core.QIODeviceBase.OpenModeFlag.WriteOnly)
                    pixmap.save(buffer, "PNG")
                    super().__init__(
                        data=bytes(ba.data()),
                        path=path,
                        header=header,
                        caption=caption,
                        title=title,
                    )