From 640f3ce9ea32b762945343187fd88641874080da Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Thu, 12 Nov 2026 20:59:18 +0100 Subject: [PATCH 01/10] docs: migrate to zensical, with offscreen theme-aware screenshots and animations Replace mkdocs + mkdocs-material with zensical (native `zensical.toml`, modern theme variant, light/dark palettes, navigation tabs and sections, instant navigation and link previews). Screenshots are no longer taken by a macro during the build (which exec'd the first code block of each page). Instead, `docs/_gen_media.py` runs as a prepare step before `zensical build`: - the examples are real, runnable scripts in `docs/examples/`, included in the pages with snippets - each one is rendered offscreen, once per theme, with Fusion and palettes that match the site, at 2x, in a subprocess per job (in parallel), and cached by content hash - `docs/_scenes.py` scripts animations for widgets that benefit from them, driven with synthetic mouse and keyboard input, recorded as animated WebP - pages show the light or dark variant to match the site's color scheme The `show_members` macro now also finds signals inherited from superqt base classes (with their comments as descriptions), separates properties, and lists Qt methods that superqt reimplements and documents. The home page and the widgets index are galleries of the rendered widgets. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 +- CONTRIBUTING.md | 22 + docs/_gen_media.py | 19 + docs/_macros.py | 301 ++++++---- docs/_media.py | 632 +++++++++++++++++++++ docs/_scenes.py | 233 ++++++++ docs/examples/code_syntax_highlight.py | 33 ++ docs/examples/colormap_catalog.py | 11 + docs/examples/fonticon.py | 14 + docs/examples/iconify.py | 13 + docs/examples/qcollapsible.py | 14 + docs/examples/qcolorcombobox.py | 17 + docs/examples/qcolormap.py | 18 + docs/examples/qdoublerangeslider.py | 13 + docs/examples/qdoubleslider.py | 13 + docs/examples/qelidinglabel.py | 15 + docs/examples/qenumcombobox.py | 20 + docs/examples/qflowlayout.py | 19 + docs/examples/qlabeleddoublerangeslider.py | 13 + docs/examples/qlabeleddoubleslider.py | 13 + docs/examples/qlabeledrangeslider.py | 12 + docs/examples/qlabeledslider.py | 12 + docs/examples/qlargeintspinbox.py | 12 + docs/examples/qquantity.py | 9 + docs/examples/qrangeslider.py | 12 + docs/examples/qsearchablecombobox.py | 11 + docs/examples/qsearchablelistwidget.py | 11 + docs/examples/qsearchabletreewidget.py | 21 + docs/examples/qtoggleswitch.py | 10 + docs/examples/showcase.py | 38 ++ docs/images/favicon.svg | 1 + docs/index.md | 62 +- docs/stylesheets/extra.css | 185 ++++++ docs/utilities/code_syntax_highlight.md | 40 +- docs/utilities/fonticon.md | 59 +- docs/utilities/iconify.md | 20 +- docs/widgets/colormap_catalog.md | 18 +- docs/widgets/index.md | 87 +-- docs/widgets/qcollapsible.md | 21 +- docs/widgets/qcolorcombobox.md | 24 +- docs/widgets/qcolormap.md | 25 +- docs/widgets/qdoublerangeslider.md | 20 +- docs/widgets/qdoubleslider.md | 20 +- docs/widgets/qelidinglabel.md | 22 +- docs/widgets/qenumcombobox.md | 26 +- docs/widgets/qflowlayout.md | 26 +- docs/widgets/qlabeleddoublerangeslider.md | 20 +- docs/widgets/qlabeleddoubleslider.md | 19 +- docs/widgets/qlabeledrangeslider.md | 19 +- docs/widgets/qlabeledslider.md | 19 +- docs/widgets/qlargeintspinbox.md | 20 +- docs/widgets/qquantity.md | 16 +- docs/widgets/qrangeslider.md | 40 +- docs/widgets/qsearchablecombobox.md | 17 +- docs/widgets/qsearchablelistwidget.md | 18 +- docs/widgets/qsearchabletreewidget.md | 27 +- docs/widgets/qtoggleswitch.md | 17 +- mkdocs.yml | 56 -- pyproject.toml | 12 +- zensical.toml | 229 ++++++++ 60 files changed, 2133 insertions(+), 635 deletions(-) create mode 100644 docs/_gen_media.py create mode 100644 docs/_media.py create mode 100644 docs/_scenes.py create mode 100644 docs/examples/code_syntax_highlight.py create mode 100644 docs/examples/colormap_catalog.py create mode 100644 docs/examples/fonticon.py create mode 100644 docs/examples/iconify.py create mode 100644 docs/examples/qcollapsible.py create mode 100644 docs/examples/qcolorcombobox.py create mode 100644 docs/examples/qcolormap.py create mode 100644 docs/examples/qdoublerangeslider.py create mode 100644 docs/examples/qdoubleslider.py create mode 100644 docs/examples/qelidinglabel.py create mode 100644 docs/examples/qenumcombobox.py create mode 100644 docs/examples/qflowlayout.py create mode 100644 docs/examples/qlabeleddoublerangeslider.py create mode 100644 docs/examples/qlabeleddoubleslider.py create mode 100644 docs/examples/qlabeledrangeslider.py create mode 100644 docs/examples/qlabeledslider.py create mode 100644 docs/examples/qlargeintspinbox.py create mode 100644 docs/examples/qquantity.py create mode 100644 docs/examples/qrangeslider.py create mode 100644 docs/examples/qsearchablecombobox.py create mode 100644 docs/examples/qsearchablelistwidget.py create mode 100644 docs/examples/qsearchabletreewidget.py create mode 100644 docs/examples/qtoggleswitch.py create mode 100644 docs/examples/showcase.py create mode 100644 docs/images/favicon.svg create mode 100644 docs/stylesheets/extra.css delete mode 100644 mkdocs.yml create mode 100644 zensical.toml diff --git a/.gitignore b/.gitignore index a610993b..e37b0842 100644 --- a/.gitignore +++ b/.gitignore @@ -81,5 +81,5 @@ src/superqt/_version.py screenshots .mypy_cache -docs/_auto_images/ +docs/_generated/ uv.lock diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 637ce5d1..2f1fb6b7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,3 +49,25 @@ All widgets should try to match the native Qt API as much as possible: ## Testing Tests can be run in the current environment with `pytest`. + +## Documentation + +The documentation is built with [Zensical](https://zensical.org). Widget +screenshots and animations are rendered from the runnable scripts in +`docs/examples/` in a separate step, before building (outputs are cached, so +reruns only render what changed): + +```bash +uv run --group docs python docs/_gen_media.py # renders into docs/_generated/ +uv run --group docs zensical serve # preview at http://localhost:8000 +``` + +To document a new widget: + +1. Add a runnable example, `docs/examples/.py`, that shows one window. +2. Add a page, `docs/widgets/.md`, that shows the example with + `{{ show_widget() }}`, includes its code with a (block-style) snippet in a + `python` code block, and lists its API with + `{{ show_members("superqt.") }}` (see the other pages). Add the page + to `nav` in `zensical.toml`, and a `card` for it in `docs/widgets/index.md`. +3. Optionally, set the window size or record an animation in `docs/_scenes.py`. diff --git a/docs/_gen_media.py b/docs/_gen_media.py new file mode 100644 index 00000000..f98fa7ce --- /dev/null +++ b/docs/_gen_media.py @@ -0,0 +1,19 @@ +"""Render the widget screenshots and animations used in the docs. + +Each `docs/examples/.py` is run offscreen, once per theme (light and dark), +and the window it shows is saved to `docs/_generated/-.png`. Examples +with a scene in `docs/_scenes.py` are also recorded as `-.webp` +(animated). Outputs are cached by content hash, so unchanged examples are skipped. + + uv run --group docs python docs/_gen_media.py # everything + uv run --group docs python docs/_gen_media.py qcollapsible --force +""" + +import sys +from pathlib import Path + +if __name__ == "__main__": + sys.path.insert(0, str(Path(__file__).parent)) + from _media import main + + sys.exit(main(description=__doc__.splitlines()[0])) diff --git a/docs/_macros.py b/docs/_macros.py index 5c65c55b..fe7ff266 100644 --- a/docs/_macros.py +++ b/docs/_macros.py @@ -1,136 +1,203 @@ -import sys +"""Macros for the superqt docs (see `[project.plugins.macros]` in zensical.toml).""" + +from __future__ import annotations + +import ast +import inspect +import json from enum import EnumMeta +from functools import cache from importlib import import_module from pathlib import Path -from textwrap import dedent -from typing import TYPE_CHECKING +from textwrap import dedent, indent +from typing import TYPE_CHECKING, Any -from jinja2 import pass_context -from qtpy.QtCore import QObject, Signal +from qtpy.QtCore import Property, QObject, Signal if TYPE_CHECKING: - from mkdocs_macros.plugin import MacrosPlugin + from collections.abc import Iterator -EXAMPLES = Path(__file__).parent.parent / "examples" -IMAGES = Path(__file__).parent / "_auto_images" -IMAGES.mkdir(exist_ok=True, parents=True) +DOCS = Path(__file__).parent +MANIFEST = DOCS / "_generated" / "manifest.json" +QT_DOCS = "https://doc.qt.io/qt-6/{}.html" -def define_env(env: "MacrosPlugin"): +def define_env(env: Any) -> None: @env.macro - @pass_context - def show_widget(context, width: int = 500) -> list[Path]: - # extract all fenced code blocks starting with "python" - page = context["page"] - dest = IMAGES / f"{page.title}.png" - if "build" in sys.argv: - dest.unlink(missing_ok=True) - - codeblocks = [ - b[6:].strip() - for b in page.markdown.split("```") - if b.startswith("python") - ] - src = codeblocks[0].strip() - src = src.replace( - "QApplication([])", "QApplication.instance() or QApplication([])" + def show_widget(name: str | None = None) -> str: + """Theme-aware screenshot (or animation) of `docs/examples/.py`. + + `name` defaults to the name of the page. + """ + page = env.variables["page"] + name = name or Path(page.path).stem + info = _manifest().get(name) + if info is None: + raise ValueError( + f"No screenshot for {name!r}: add docs/examples/{name}.py, and run " + "`uv run --group docs python docs/_gen_media.py`" ) - src = src.replace("app.exec_()", "app.processEvents()") - - exec(src) - _grab(dest, width) - return ( - f"![{page.title}](../{dest.parent.name}/{dest.name})" - f"{{ loading=lazy; width={width} }}\n\n" + root = "../" * Path(page.path).as_posix().count("/") + "_generated/" + animated = "animation" in info + ext, size = ("webp", info["animation"]) if animated else ("png", info) + attrs = f'width="{size["width"]}" height="{size["height"]}" loading=lazy' + imgs = "\n".join( + f"![{page.title}]({root}{name}-{theme}.{ext}#only-{theme}){{ {attrs} }}" + for theme in ("light", "dark") ) + return f'
\n{imgs}\n
\n' @env.macro - def show_members(cls: str): - # import class - module, name = cls.rsplit(".", 1) - _cls = getattr(import_module(module), name) - - first_q = next( - ( - b.__name__ - for b in _cls.__mro__ - if issubclass(b, QObject) and ".Qt" in b.__module__ - ), - None, + def card(page_ref: str, title: str, description: str) -> str: + """Gallery card linking to `page_ref`, with its widget's screenshot.""" + page = env.variables["page"] + name = Path(page_ref).stem + thumb = "" + if info := _manifest().get(name): + root = "../" * Path(page.path).as_posix().count("/") + "_generated/" + attrs = f'width="{info["width"]}" loading=lazy' + thumb = "".join( + f"![]({root}{name}-{theme}.png#only-{theme}){{ {attrs} }}" + for theme in ("light", "dark") + ) + return ( + f'[{thumb}' + f'{title}' + f"{description}]({page_ref}){{ .sq-card }}" ) - inherited_members = set() - for base in _cls.__mro__: - if issubclass(base, QObject) and ".Qt" in base.__module__: - inherited_members.update( - {k for k in dir(base) if not k.startswith("_")} - ) - - new_signals = { - k - for k, v in vars(_cls).items() - if not k.startswith("_") and isinstance(v, Signal) - } - - self_members = { - k - for k in dir(_cls) - if not k.startswith("_") and k not in inherited_members | new_signals - } - - enums = [] - for m in list(self_members): - if isinstance(getattr(_cls, m), EnumMeta): - self_members.remove(m) - enums.append(m) - - out = "" - if first_q: - url = f"https://doc.qt.io/qt-6/{first_q.lower()}.html" - out += f"## Qt Class\n\n`{first_q}`\n\n" - - out += "" - - if new_signals: - out += "## Signals\n\n" - for sig in new_signals: - out += f"### `{sig}`\n\n" - - if enums: - out += "## Enums\n\n" - for e in enums: - out += f"### `{_cls.__name__}.{e}`\n\n" - for m in getattr(_cls, e): - out += f"- `{m.name}`\n\n" - - if self_members: - out += dedent( - f""" - ## Methods - - ::: {cls} - options: - heading_level: 3 - show_source: False - show_inherited_members: false - show_signature_annotations: True - members: {sorted(self_members)} - docstring_style: numpy - show_bases: False - show_root_toc_entry: False - show_root_heading: False - """ + @env.macro + def show_members(cls_path: str) -> str: + """API sections for a widget: its Qt base class, signals, enums and methods.""" + module, name = cls_path.rsplit(".", 1) + cls = getattr(import_module(module), name) + qt_base = next((b for b in cls.__mro__ if _is_qt(b)), None) + qt_members = {m for b in cls.__mro__ if _is_qt(b) for m in dir(b)} + signals = dict(_signals(cls)) + + out = ["## API\n"] + if qt_base is not None: + link = f"[`{qt_base.__name__}`]({QT_DOCS.format(qt_base.__name__.lower())})" + out.append( + f'!!! abstract "Subclass of {qt_base.__name__}"\n\n' + f" `{cls.__name__}` inherits all of {link}'s methods, signals, and " + "properties. Only those that `superqt` adds or changes are listed " + "here.\n" ) - return out - + if signals: + out.append("### Signals\n") + for sig, (args, doc) in signals.items(): + out.append(f"- `{sig}({args})`" + (f": {doc}" if doc else "")) + out.append("") -def _grab(dest: str | Path, width) -> list[Path]: - """Grab the top widgets of the application.""" - from qtpy.QtWidgets import QApplication - - w = QApplication.topLevelWidgets()[-1] - w.setFixedWidth(width) - w.activateWindow() - w.setMinimumHeight(40) - w.grab().save(str(dest)) + public = {m for m in dir(cls) if not m.startswith("_")} + enums = sorted( + m for m in public - qt_members if isinstance(getattr(cls, m), EnumMeta) + ) + if enums: + out.append("### Enums\n") + for enum_name in enums: + values = ", ".join(f"`{m.name}`" for m in getattr(cls, enum_name)) + out.append(f"`{cls.__name__}.{enum_name}`\n: {values}\n") + + names = (public - qt_members) | _documented_overrides(cls, public & qt_members) + names -= set(signals) | set(enums) | {n for n in names if n.isupper()} + props = sorted(n for n in names if isinstance(getattr(cls, n), Property)) + methods = sorted(names - set(props)) + for title, members in (("Properties", props), ("Methods", methods)): + if members: + out.append(f"### {title}\n\n{_mkdocstrings(cls_path, members)}") + return "\n".join(out) + + +def _mkdocstrings(cls_path: str, members: list[str]) -> str: + options = f""" + options: + heading_level: 4 + show_root_heading: false + show_root_toc_entry: false + show_docstring_description: true + inherited_members: true + show_if_no_docstring: true + members: {members} + """ + return f"::: {cls_path}\n{indent(dedent(options), ' ')}" + + +# Qt virtuals that superqt reimplements as implementation details +_VIRTUALS = {"event", "eventFilter", "initStyleOption", "sizeHint", "minimumSizeHint"} +_VIRTUALS |= {"checkStateSet", "nextCheckState", "setStyleSheet"} + + +def _documented_overrides(cls: type, names: set[str]) -> set[str]: + """Qt methods that superqt reimplements and documents (e.g. `value()`).""" + out = set() + for name in names - _VIRTUALS: + if name.endswith("Event"): + continue + owner = next(b for b in cls.__mro__ if name in vars(b)) + if owner.__module__.startswith("superqt") and inspect.getdoc(vars(owner)[name]): + out.add(name) + return out + + +@cache +def _manifest() -> dict[str, dict]: + return json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {} + + +def _is_qt(cls: type) -> bool: + return issubclass(cls, QObject) and ".Qt" in cls.__module__ + + +def _signals(cls: type) -> Iterator[tuple[str, tuple[str, str]]]: + """Signals declared on `cls` or its superqt bases: name -> (arguments, doc). + + The doc is a string literal after the signal (an attribute docstring), or the + comment above it, or a trailing `# emitted when...` comment. + """ + seen: set[str] = set() + for base in cls.__mro__: + if not base.__module__.startswith("superqt"): + continue + lines, _ = inspect.getsourcelines(base) + body = ast.parse(dedent("".join(lines))).body[0].body # type: ignore + for node, after in zip(body, [*body[1:], None], strict=True): + if not ( + isinstance(node, ast.Assign) + and isinstance(node.targets[0], ast.Name) + and isinstance(getattr(base, node.targets[0].id, None), Signal) + ): + continue + sig = node.targets[0].id + if sig.startswith("_") or sig in seen: + continue + seen.add(sig) + call = node.value + args = ", ".join(ast.unparse(a) for a in getattr(call, "args", [])) + if ( + isinstance(after, ast.Expr) + and isinstance(after.value, ast.Constant) + and isinstance(after.value.value, str) + ): + doc = " ".join(after.value.value.split()) + elif above := _comment_above(lines, node.lineno - 1): + doc = above + else: + comment = lines[node.lineno - 1].partition("#")[2].strip() + doc = comment.capitalize() if comment.startswith("emitted") else "" + yield sig, (args, doc) + + +def _comment_above(lines: list[str], index: int) -> str: + comments: list[str] = [] + while index > 0 and (line := lines[index - 1].strip()).startswith("#"): + comments.insert(0, line.lstrip("# ")) + index -= 1 + text = "" + for comment in comments: # (join sentences that were split across lines) + if text and text[-1] not in ".,;:" and comment[:1].isupper(): + text += "." + text = f"{text} {comment}" if text else comment + return text diff --git a/docs/_media.py b/docs/_media.py new file mode 100644 index 00000000..e3eaf45e --- /dev/null +++ b/docs/_media.py @@ -0,0 +1,632 @@ +"""Offscreen renderer for the docs' widget screenshots and animations. + +Run it with `docs/_gen_media.py`; animations and capture options live in +`docs/_scenes.py`. +""" + +from __future__ import annotations + +import argparse +import hashlib +import inspect +import json +import os +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor, as_completed +from contextlib import contextmanager +from dataclasses import dataclass, replace +from pathlib import Path +from typing import TYPE_CHECKING, Any + +SCALE = 2 # device pixel ratio of the rendered images +os.environ["QT_QPA_PLATFORM"] = "offscreen" # deterministic, and headless +os.environ["QT_SCALE_FACTOR"] = str(SCALE) + +from PIL import Image # noqa: E402 +from qtpy import API_NAME, QT_VERSION, QtWidgets # noqa: E402 +from qtpy.QtCore import ( # noqa: E402 + QPoint, + QPointF, + QRect, + QRectF, + QSize, + Qt, + qInstallMessageHandler, +) +from qtpy.QtGui import ( # noqa: E402 + QColor, + QFont, + QFontDatabase, + QGuiApplication, + QImage, + QPainter, + QPainterPath, + QPalette, + QPen, +) +from qtpy.QtTest import QTest # noqa: E402 +from qtpy.QtWidgets import QApplication, QWidget # noqa: E402 + +from superqt.sliders import _range_style # noqa: E402 + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + +DOCS = Path(__file__).parent +EXAMPLES = DOCS / "examples" +OUT = DOCS / "_generated" +MANIFEST = OUT / "manifest.json" +MARGIN = 14 # logical px of window background around each capture +FPS = 30 +FONTS = ("Inter", "Inter Variable", "Helvetica Neue", "Segoe UI", "Noto Sans") + +# Fusion palettes, tuned to sit on the light and dark zensical "modern" theme. +# Keep `Highlight` in sync with `--sq-accent` in docs/stylesheets/extra.css. +THEMES: dict[str, dict[str, str]] = { + "light": { + "Window": "#f3f4f7", + "Button": "#fbfbfc", + "Base": "#ffffff", + "AlternateBase": "#eef0f4", + "Text": "#1d2129", + "WindowText": "#1d2129", + "ButtonText": "#1d2129", + "PlaceholderText": "#868c97", + "Highlight": "#4d5bd8", + "HighlightedText": "#ffffff", + "ToolTipBase": "#ffffff", + "ToolTipText": "#1d2129", + "Link": "#4d5bd8", + }, + "dark": { + "Window": "#1b1e25", + "Button": "#272b34", + "Base": "#13151a", + "AlternateBase": "#1f232a", + "Text": "#e3e6ec", + "WindowText": "#e3e6ec", + "ButtonText": "#e3e6ec", + "PlaceholderText": "#7c8390", + "Highlight": "#6f7cf2", + "HighlightedText": "#ffffff", + "ToolTipBase": "#272b34", + "ToolTipText": "#e3e6ec", + "Link": "#8f9aff", + }, +} + +PAD = 10 # logical px of window background around an outlined main window +# (backdrop, window outline): behind windows that don't fill the image +BACKDROPS = {"light": ("#e3e6eb", "#c5cad3"), "dark": ("#0f1115", "#3a3f4b")} + + +# --------------------------------------------------------------------------- +# Specs: how each example is captured (registered in docs/_scenes.py) + + +@dataclass +class Spec: + """How to capture one example.""" + + width: int | None = None # resize the window to this width (logical px) + height: int | None = None # ... and/or this height + setup: Callable[[QWidget], Any] | None = None # called before capturing + scene: Callable[[Recorder, QWidget], Any] | None = None # records an animation + + def source(self) -> str: + funcs = [f for f in (self.setup, self.scene) if f is not None] + return repr((self.width, self.height)) + "".join(map(inspect.getsource, funcs)) + + +SPECS: dict[str, Spec] = {} + + +def spec(name: str, **kwargs: Any) -> Spec: + """Register capture options for `docs/examples/.py`.""" + SPECS[name] = Spec(**kwargs) + return SPECS[name] + + +def scene(name: str, **kwargs: Any) -> Callable: + """Decorator: register `func(recorder, window)` as the animation for `name`.""" + + def _deco(func: Callable) -> Callable: + spec(name, scene=func, **kwargs) + return func + + return _deco + + +# --------------------------------------------------------------------------- +# Capturing + + +@dataclass +class Frame: + """The visible windows (global geometry, image) and cursor at one instant.""" + + windows: list[tuple[QRect, QImage]] + cursor: QPointF | None = None + pressed: bool = False + t: float = 0.0 + + +def _capture(main: QWidget, cursor: QPointF | None = None, pressed=False) -> Frame: + # the main window first, then popups etc. on top of it + tops = [main] + [ + w for w in QApplication.topLevelWidgets() if w is not main and w.isVisible() + ] + windows = [ + (QRect(w.mapToGlobal(QPoint(0, 0)), w.size()), w.grab().toImage()) + for w in tops + if w.isVisible() + ] + return Frame(windows, cursor, pressed, time.perf_counter()) + + +def _compose(frames: list[Frame], theme: str) -> list[QImage]: + """Paint frames onto canvases with a common size (the union of all windows). + + If the main window always fills the canvas, it's drawn as is, on a margin of + its own background. Otherwise (popups, resizing) windows are outlined on a + backdrop, so that you can see where they end. + """ + windows = [frame.windows[0][0] for frame in frames] + flat = all(len(f.windows) == 1 and f.windows[0][0] == windows[0] for f in frames) + pad = 0 if flat else PAD + bounds = QRect() + for frame in frames: + for i, (rect, _) in enumerate(frame.windows): + bounds = bounds.united( + rect.adjusted(-pad, -pad, pad, pad) if i == 0 else rect + ) + bounds.adjust(-MARGIN, -MARGIN, MARGIN, MARGIN) + + colors = THEMES[theme] + backdrop, outline = (QColor(c) for c in BACKDROPS[theme]) + images = [] + for frame in frames: + img = QImage(bounds.size() * SCALE, QImage.Format.Format_ARGB32_Premultiplied) + img.setDevicePixelRatio(SCALE) + img.fill(QColor(colors["Window"]) if flat else backdrop) + painter = QPainter(img) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + for i, (rect, win_img) in enumerate(frame.windows): + rect = rect.translated(-bounds.topLeft()) + if not flat: + panel = rect.adjusted(-pad, -pad, pad, pad) if i == 0 else rect + painter.fillRect(panel.translated(0, 2), QColor(0, 0, 0, 28)) # shadow + painter.fillRect(panel, QColor(colors["Window"])) + painter.setPen(QPen(outline, 1)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRect(QRectF(panel).adjusted(-0.5, -0.5, 0.5, 0.5)) + painter.drawImage(rect.topLeft(), win_img) + if frame.cursor is not None: + _draw_cursor(painter, frame.cursor - QPointF(bounds.topLeft()), frame) + painter.end() + images.append(img) + return images + + +_ARROW = [(0, 0), (0, 15.5), (4, 12), (6.6, 18), (9, 17), (6.5, 11), (11.5, 11)] + + +def _draw_cursor(painter: QPainter, pos: QPointF, frame: Frame) -> None: + if frame.pressed: + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(120, 130, 255, 90)) + painter.drawEllipse(pos, 11, 11) + path = QPainterPath() + path.moveTo(pos + QPointF(*_ARROW[0])) + for x, y in _ARROW[1:]: + path.lineTo(pos + QPointF(x, y)) + path.closeSubpath() + painter.setPen(QPen(QColor("white"), 1.3)) + painter.setBrush(QColor(20, 20, 20)) + painter.drawPath(path) + + +class Recorder: + """Drives a window with synthetic input, recording frames in real time. + + Positions are in the coordinates of the widget they're given with (its center + by default), and the cursor is drawn into the frames. + """ + + def __init__(self, window: QWidget, fps: int = FPS) -> None: + self.window = window + self.frames: list[Frame] = [] + self._interval = 1 / fps + self._next = time.perf_counter() + self._cursor: QPointF | None = None + self._pressed = False + + # -- primitives -- + + def frame(self) -> None: + """Process events until the next frame is due, then capture it.""" + # (if we fell behind, capture now: frame durations come from timestamps) + self._next = max(self._next + self._interval, time.perf_counter()) + while (remaining := self._next - time.perf_counter()) > 0: + QTest.qWait(max(1, int(remaining * 1000))) + self.frames.append(_capture(self.window, self._cursor, self._pressed)) + + def wait(self, seconds: float) -> None: + for _ in range(max(1, round(seconds / self._interval))): + self.frame() + + def _global(self, widget: QWidget | None, pos: QPoint | QPointF | None) -> QPointF: + widget = widget or self.window + if pos is None: + pos = widget.rect().center() + return QPointF(widget.mapToGlobal(QPointF(pos))) + + def _send(self, kind: str) -> None: + assert self._cursor is not None + win = self.window.windowHandle() + origin = QPointF(self.window.mapToGlobal(QPoint(0, 0))) + local = (self._cursor - origin).toPoint() + btn, mod = Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier + if kind == "move": + if self._pressed or self.window.rect().contains(local): + QTest.mouseMove(win, local) + elif kind == "press": + QTest.mousePress(win, btn, mod, local) + else: + QTest.mouseRelease(win, btn, mod, local) + + # -- gestures -- + + def move( + self, + widget: QWidget | None = None, + pos: QPoint | QPointF | None = None, + duration: float = 0.5, + ) -> None: + """Glide the cursor to `pos` in `widget` (dragging, if pressed).""" + end = self._global(widget, pos) + if self._cursor is None: # the cursor enters from below + self._cursor = end + QPointF(40, 60) + start = QPointF(self._cursor) + steps = max(1, round(duration / self._interval)) + for i in range(1, steps + 1): + t = _ease(i / steps) + self._cursor = start + (end - start) * t + self._send("move") + self.frame() + + def press(self) -> None: + self._pressed = True + self._send("press") + self.wait(0.12) + + def release(self) -> None: + self._pressed = False + self._send("release") + self.wait(0.12) + + def click(self, widget: QWidget | None = None, pos=None, **kwargs: Any) -> None: + self.move(widget, pos, **kwargs) + self.press() + self.release() + + def drag(self, widget: QWidget | None, start, end, duration: float = 0.8) -> None: + self.move(widget, start) + self.press() + self.move(widget, end, duration) + self.release() + + def type(self, widget: QWidget, text: str, interval: float = 0.09) -> None: + widget.setFocus() + for char in text: + QTest.keyClick(widget, char) + self.wait(interval) + + def key(self, widget: QWidget, key: Qt.Key, times: int = 1, interval=0.1) -> None: + for _ in range(times): + QTest.keyClick(widget, key) + self.wait(interval) + + def leave(self, duration: float = 0.4) -> None: + """Move the cursor off the bottom of the window, and hide it.""" + bottom = self.window.rect().bottomRight() + QPoint(30, 40) + self.move(None, bottom, duration) + self._cursor = None + + def resize( + self, + width: int | None = None, + height: int | None = None, + duration: float = 1.0, + fit_height: bool = False, + ) -> None: + """Animate the window size (with `fit_height`, height follows the width).""" + start = self.window.size() + end = QSize(width or start.width(), height or start.height()) + steps = max(1, round(duration / self._interval)) + for i in range(1, steps + 1): + t = _ease(i / steps) + w = round(start.width() + (end.width() - start.width()) * t) + h = round(start.height() + (end.height() - start.height()) * t) + if fit_height: + h = self.window.heightForWidth(w) + self.window.resize(w, h) + self.frame() + + +def _ease(t: float) -> float: + return 4 * t**3 if t < 0.5 else 1 - (-2 * t + 2) ** 3 / 2 + + +# --------------------------------------------------------------------------- +# Running examples + + +class _AppProxy: + """Stands in for the `QApplication` that an example creates.""" + + def __init__(self, app: QApplication) -> None: + self._app = app + + def exec(self, *_: Any) -> int: + return 0 + + exec_ = exec + + def __getattr__(self, name: str) -> Any: + return getattr(self._app, name) + + +class _AppShimMeta(type): + def __call__(cls, *_: Any, **__: Any) -> _AppProxy: + return _AppProxy(QApplication.instance()) + + def __getattr__(cls, name: str) -> Any: + return getattr(QApplication, name) + + +class _AppShim(metaclass=_AppShimMeta): + pass + + +@contextmanager +def _patched_qapplication() -> Iterator[None]: + """Make `QApplication([])` return the running app, and `exec()` return at once.""" + QtWidgets.QApplication = _AppShim # type: ignore[misc] + try: + yield + finally: + QtWidgets.QApplication = QApplication # type: ignore[misc] + + +def _run_example(name: str) -> tuple[QWidget, dict]: + """Run an example, returning the window it shows (and its namespace).""" + path = EXAMPLES / f"{name}.py" + code = compile(path.read_text(), str(path), "exec") + namespace = {"__name__": "__main__", "__file__": str(path)} + with _patched_qapplication(): + try: + exec(code, namespace) + except SystemExit: + pass + shown = [w for w in QApplication.topLevelWidgets() if w.isVisible()] + if len(shown) != 1: + raise RuntimeError(f"{path.name} should show one window, not {len(shown)}") + QTest.qWaitForWindowExposed(shown[0]) + return shown[0], namespace + + +def _clear_focus() -> None: + if widget := QApplication.focusWidget(): + widget.clearFocus() + + +# --------------------------------------------------------------------------- +# Workers + + +_QUIET = ("propagateSizeHints", "Populating font family aliases") + + +def _qt_message_handler(mode: Any, context: Any, message: str) -> None: + if not message.startswith(_QUIET) and "propagateSizeHints" not in message: + print(message, file=sys.stderr) + + +def _make_app() -> QApplication: + qInstallMessageHandler(_qt_message_handler) + app = QApplication([]) + app.setStyle("Fusion") + families = set(QFontDatabase.families()) + if family := next((f for f in FONTS if f in families), None): + app.setFont(QFont(family, 10)) + return app + + +def _set_theme(theme: str) -> None: + colors = THEMES[theme] + palette = QPalette(QColor(colors["Button"]), QColor(colors["Window"])) + for role, color in colors.items(): + palette.setColor(getattr(QPalette.ColorRole, role), QColor(color)) + disabled = QColor(colors["PlaceholderText"]) + for role in ("Text", "WindowText", "ButtonText"): + role_ = getattr(QPalette.ColorRole, role) + palette.setColor(QPalette.ColorGroup.Disabled, role_, disabled) + QApplication.setPalette(palette) + + # QRangeSlider's bar color is hard-coded per OS; use the theme's accent instead, + # so the docs look the same wherever they're built + accent = QColor(colors["Highlight"]) + _range_style.SYSTEM_STYLE = replace( + _range_style.LINUX_STYLE, + brush_active=accent.name(), + brush_inactive=accent.name(), + brush_disabled=colors["PlaceholderText"], + pen_active=accent.darker(125).name(), + pen_inactive=accent.darker(125).name(), + pen_disabled=colors["PlaceholderText"], + ) + if hasattr(hints := QGuiApplication.styleHints(), "setColorScheme"): + scheme = Qt.ColorScheme.Dark if theme == "dark" else Qt.ColorScheme.Light + hints.setColorScheme(scheme) + + +def _to_pil(img: QImage) -> Image.Image: + img = img.convertToFormat(QImage.Format.Format_RGBA8888) + ptr = img.constBits() + if hasattr(ptr, "setsize"): # PyQt + ptr.setsize(img.sizeInBytes()) + size = (img.width(), img.height()) + return Image.frombuffer("RGBA", size, bytes(ptr), "raw", "RGBA", 0, 1) + + +def _save_animation(frames: list[Frame], images: list[QImage], dest: Path) -> None: + pils: list[Image.Image] = [] + durations: list[int] = [] + times = [f.t for f in frames] + [frames[-1].t + 1 / FPS] + for i, img in enumerate(images): + pil = _to_pil(img).convert("RGB") + ms = round((times[i + 1] - times[i]) * 1000) + if pils and pil.tobytes() == pils[-1].tobytes(): + durations[-1] += ms # merge repeated frames + else: + pils.append(pil) + durations.append(ms) + durations[-1] += 1200 # rest on the last frame before looping + pils[0].save( + dest, + save_all=True, + append_images=pils[1:], + duration=durations, + loop=0, + lossless=True, + method=4, + ) + + +def _render(name: str, theme: str) -> dict[str, Any]: + """Render one example in one theme (in a fresh process: see `_work`).""" + _set_theme(theme) + spec = SPECS.get(name, Spec()) + window, _namespace = _run_example(name) # (keeps the example's objects alive) + if spec.width or spec.height: + width = spec.width or window.width() + height = spec.height or window.heightForWidth(width) + if height <= 0: + height = window.sizeHint().height() + window.resize(width, height) + if spec.setup is not None: + spec.setup(window) + _clear_focus() # no text cursor or focus ring in stills + QTest.qWait(50) + + still = _compose([_capture(window)], theme)[0] + _to_pil(still).save(OUT / f"{name}-{theme}.png", optimize=True) + info: dict[str, Any] = { + "width": still.width() // SCALE, + "height": still.height() // SCALE, + } + if spec.scene is not None: + rec = Recorder(window) + rec.wait(0.8) + spec.scene(rec, window) + rec.wait(0.3) + images = _compose(rec.frames, theme) + _save_animation(rec.frames, images, OUT / f"{name}-{theme}.webp") + info["animation"] = { + "width": images[0].width() // SCALE, + "height": images[0].height() // SCALE, + } + return info + + +# --------------------------------------------------------------------------- +# Main + + +def _work(name: str, theme: str) -> None: + """Render in a worker process, print the result, and exit without Qt teardown.""" + import _scenes # noqa: F401 (registers specs) + + app = _make_app() # noqa: F841 + print(_RESULT + json.dumps(_render(name, theme)), flush=True) + os._exit(0) + + +_RESULT = "@@result " + + +def _run_job(name: str, theme: str) -> tuple[dict | None, str]: + cmd = [sys.executable, str(DOCS / "_gen_media.py"), "--worker", name, theme] + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + for line in proc.stdout.splitlines(): + if line.startswith(_RESULT): + return json.loads(line[len(_RESULT) :]), proc.stderr + return None, proc.stderr or f"exited with {proc.returncode}" + + +def _hash(name: str) -> str: + src = [ + (EXAMPLES / f"{name}.py").read_text(), + Path(__file__).read_text(), + SPECS.get(name, Spec()).source(), + f"{API_NAME} {QT_VERSION}", + ] + return hashlib.sha256("\0".join(src).encode()).hexdigest()[:16] + + +def _outputs_exist(name: str, info: dict) -> bool: + exts = ["png"] + (["webp"] if "animation" in info else []) + return all((OUT / f"{name}-{t}.{e}").exists() for t in THEMES for e in exts) + + +def main(argv: list[str] | None = None, description: str = "") -> int: + parser = argparse.ArgumentParser(description=description) + parser.add_argument("names", nargs="*", help="examples to render (default: all)") + parser.add_argument("-f", "--force", action="store_true", help="ignore the cache") + parser.add_argument("-j", "--jobs", type=int, default=os.cpu_count()) + parser.add_argument("--worker", nargs=2, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + if args.worker: + _work(*args.worker) + + import _scenes # noqa: F401 (registers specs) + + available = sorted(p.stem for p in EXAMPLES.glob("*.py")) + if unknown := set(args.names) - set(available): + parser.error(f"no such example(s): {', '.join(sorted(unknown))}") + OUT.mkdir(exist_ok=True) + manifest = json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {} + manifest = {k: v for k, v in manifest.items() if k in available} + + todo = [ + name + for name in args.names or available + if args.force + or manifest.get(name, {}).get("hash") != _hash(name) + or not _outputs_exist(name, manifest[name]) + ] + print(f"rendering {len(todo)} of {len(args.names or available)} examples") + + t0 = time.perf_counter() + failed: set[str] = set() + jobs = {(name, theme) for name in todo for theme in THEMES} + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + futures = {pool.submit(_run_job, *job): job for job in jobs} + for future in as_completed(futures): + (name, theme), (info, stderr) = futures[future], future.result() + if info is None: + failed.add(name) + print(f" ✗ {name} ({theme})\n{stderr}", file=sys.stderr) + continue + print(f" ✓ {name} ({theme})") + if theme == "light": + manifest[name] = {"hash": _hash(name), **info} + + for name in failed: + manifest.pop(name, None) + MANIFEST.write_text(json.dumps(dict(sorted(manifest.items())), indent=2) + "\n") + print(f"done in {time.perf_counter() - t0:.1f}s") + return 1 if failed else 0 diff --git a/docs/_scenes.py b/docs/_scenes.py new file mode 100644 index 00000000..6fe3d660 --- /dev/null +++ b/docs/_scenes.py @@ -0,0 +1,233 @@ +"""How each docs example is captured, and the animations recorded for some. + +Examples without an entry here are captured as shown, without animation. A scene +receives a `Recorder` (see `_media.py`) and the window that the example shows; +`r.wait(...)` holds still, everything else moves the cursor or types. +Scenes should end where they start, so the animation loops smoothly. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from _media import scene, spec +from qtpy.QtCore import QPoint, Qt +from qtpy.QtWidgets import QComboBox, QSlider, QStyle, QStyleOptionSlider + +from superqt import ( + QColormapComboBox, + QLabeledRangeSlider, + QSearchableComboBox, + QToggleSwitch, +) + +if TYPE_CHECKING: + from _media import Recorder + from qtpy.QtWidgets import QWidget + +# --------------------------------------------------------------------------- +# Sliders + + +def _handle(slider: QSlider, index: int = 0) -> QPoint: + """Center of a slider handle.""" + if hasattr(slider, "_handleRect"): # range sliders + return slider._handleRect(index).center() + if hasattr(slider, "_styleOption"): # superqt float sliders + opt = slider._styleOption + else: + opt = QStyleOptionSlider() + slider.initStyleOption(opt) + cc, sc = QStyle.ComplexControl.CC_Slider, QStyle.SubControl.SC_SliderHandle + return slider.style().subControlRect(cc, opt, sc, slider).center() + + +def _drag_handle(r: Recorder, slider: QSlider, index: int, fraction: float) -> None: + start = _handle(slider, index) + end = start + QPoint(round(slider.width() * fraction), 0) + r.drag(slider, start, end, duration=0.7) + r.wait(0.3) + + +def _range_scene(r: Recorder, window: QWidget) -> None: + slider = getattr(window, "_slider", window) # labeled sliders wrap a slider + _drag_handle(r, slider, 0, 0.25) + # drag the bar between the handles, then the upper handle back + bar = (_handle(slider, 0) + _handle(slider, 1)) / 2 + r.drag(slider, bar, bar - QPoint(round(slider.width() * 0.25), 0), duration=0.8) + r.wait(0.3) + _drag_handle(r, slider, 1, 0.25) + r.leave() + + +def _single_scene(r: Recorder, window: QWidget) -> None: + slider = getattr(window, "_slider", window) + _drag_handle(r, slider, 0, 0.3) + _drag_handle(r, slider, 0, -0.3) + r.leave() + + +SLIDER_WIDTH = 480 +for name in ("qrangeslider", "qdoublerangeslider"): + spec(name, width=SLIDER_WIDTH, scene=_range_scene) +for name in ("qlabeledrangeslider", "qlabeleddoublerangeslider"): + spec(name, width=SLIDER_WIDTH, scene=_range_scene) +for name in ("qdoubleslider", "qlabeledslider", "qlabeleddoubleslider"): + spec(name, width=SLIDER_WIDTH, scene=_single_scene) + + +# --------------------------------------------------------------------------- +# Buttons, containers and layouts + + +@scene("qtoggleswitch") +def _(r: Recorder, window: QWidget) -> None: + r.click(window, QPoint(22, window.height() // 2)) + r.wait(0.8) + r.click(window, QPoint(22, window.height() // 2), duration=0.2) + r.leave() + + +@scene("qcollapsible", width=340) +def _(r: Recorder, window: QWidget) -> None: + button = window.toggleButton() + r.click(button, QPoint(60, button.height() // 2)) + r.wait(0.9) + r.click(button, QPoint(60, button.height() // 2), duration=0.2) + r.wait(0.6) + r.leave() + + +@scene("qelidinglabel", width=300) +def _(r: Recorder, window: QWidget) -> None: + r.resize(150, duration=1.2) + r.wait(0.5) + r.resize(300, duration=1.2) + + +@scene("qflowlayout", width=340) +def _(r: Recorder, window: QWidget) -> None: + r.resize(170, duration=1.4, fit_height=True) + r.wait(0.5) + r.resize(340, duration=1.4, fit_height=True) + + +# --------------------------------------------------------------------------- +# Searchable widgets + + +@scene("qsearchablelistwidget", width=260, height=200) +def _(r: Recorder, window: QWidget) -> None: + r.click(window.filter_widget) + r.leave(duration=0.3) + r.type(window.filter_widget, "bar") + r.wait(0.9) + r.key(window.filter_widget, Qt.Key.Key_Backspace, times=3) + + +@scene("qsearchabletreewidget", width=320, height=260) +def _(r: Recorder, window: QWidget) -> None: + r.click(window.filter) + r.leave(duration=0.3) + r.type(window.filter, "fl") + r.wait(0.9) + r.key(window.filter, Qt.Key.Key_Backspace, times=2) + + +@scene("qsearchablecombobox", width=200) +def _(r: Recorder, window: QComboBox) -> None: + edit = window.lineEdit() + r.click(edit) + edit.selectAll() + r.leave(duration=0.3) + r.type(edit, "baz") + r.wait(0.6) + _complete(r, window) + r.wait(1.0) + window.setCurrentIndex(0) + edit.clearFocus() + + +def _complete(r: Recorder, combo: QComboBox) -> None: + """Pick the first completion, with the keyboard.""" + popup = combo.completer().popup() + r.key(popup, Qt.Key.Key_Down, interval=0.3) + r.key(popup, Qt.Key.Key_Return) + + +# --------------------------------------------------------------------------- +# Combo boxes: open the popup and pick an item + + +def _pick(r: Recorder, combo: QComboBox, index: int) -> None: + initial = combo.currentIndex() + r.click(combo) + r.wait(0.3) + view = combo.view() + r.move(view, view.visualRect(combo.model().index(index, 0)).center()) + r.wait(0.3) + r.press() + r.release() + r.wait(0.8) + r.leave() + combo.setCurrentIndex(initial) + + +@scene("qenumcombobox", width=200) +def _(r: Recorder, window: QComboBox) -> None: + _pick(r, window, 2) + + +@scene("qcolorcombobox", width=200) +def _(r: Recorder, window: QComboBox) -> None: + _pick(r, window, 2) + + +@scene("qcolormap", width=220) +def _(r: Recorder, window: QComboBox) -> None: + _pick(r, window, 2) + + +spec("colormap_catalog", width=220) + + +# --------------------------------------------------------------------------- +# Home page + + +@scene("showcase", width=420) +def _(r: Recorder, window: QWidget) -> None: + channel = window.findChild(QSearchableComboBox) + limits = window.findChild(QLabeledRangeSlider) + cmap = window.findChild(QColormapComboBox) + switch = window.findChild(QToggleSwitch) + + _drag_handle(r, limits._slider, 0, 0.25) + _pick(r, cmap, 1) + cmap.setCurrentIndex(1) + r.click(switch, QPoint(14, switch.height() // 2)) + r.wait(0.3) + edit = channel.lineEdit() + r.click(edit) + edit.selectAll() + r.leave(duration=0.3) + r.type(edit, "ch") + r.wait(0.6) + _complete(r, channel) + r.wait(1.0) + # back to the start, for the next loop + for widget in (channel, cmap): + widget.setCurrentIndex(0) + limits.setValue((30, 200)) + switch.setChecked(False) + channel.completer().popup().hide() + edit.clearFocus() + r.wait(0.1) + + +# --------------------------------------------------------------------------- +# Stills + +spec("qlargeintspinbox", width=180) +spec("qquantity", width=220) +spec("code_syntax_highlight", width=460, height=260) diff --git a/docs/examples/code_syntax_highlight.py b/docs/examples/code_syntax_highlight.py new file mode 100644 index 00000000..e75fead4 --- /dev/null +++ b/docs/examples/code_syntax_highlight.py @@ -0,0 +1,33 @@ +from qtpy.QtGui import QColor, QPalette +from qtpy.QtWidgets import QApplication, QTextEdit + +from superqt.utils import CodeSyntaxHighlight + +app = QApplication([]) + +text_area = QTextEdit() + +highlight = CodeSyntaxHighlight(text_area.document(), "python", "monokai") + +palette = text_area.palette() +palette.setColor(QPalette.Base, QColor(highlight.background_color)) +text_area.setPalette(palette) +text_area.setText( + """from argparse import ArgumentParser + +def main(): + parser = ArgumentParser() + parser.add_argument("name", help="Your name") + args = parser.parse_args() + print(f"Hello {args.name}") + + +if __name__ == "__main__": + main() +""" +) + +text_area.show() +text_area.resize(400, 200) + +app.exec() diff --git a/docs/examples/colormap_catalog.py b/docs/examples/colormap_catalog.py new file mode 100644 index 00000000..c2ec3b49 --- /dev/null +++ b/docs/examples/colormap_catalog.py @@ -0,0 +1,11 @@ +from qtpy.QtWidgets import QApplication + +from superqt.cmap import CmapCatalogComboBox + +app = QApplication([]) + +catalog_combo = CmapCatalogComboBox(interpolation="linear") +catalog_combo.setCurrentText("viridis") +catalog_combo.show() + +app.exec() diff --git a/docs/examples/fonticon.py b/docs/examples/fonticon.py new file mode 100644 index 00000000..9f5f6dfe --- /dev/null +++ b/docs/examples/fonticon.py @@ -0,0 +1,14 @@ +from fonticon_fa5 import FA5S +from qtpy.QtCore import QSize +from qtpy.QtWidgets import QApplication, QPushButton + +from superqt.fonticon import icon + +app = QApplication([]) + +btn2 = QPushButton() +btn2.setIcon(icon(FA5S.smile, color="blue")) +btn2.setIconSize(QSize(225, 225)) +btn2.show() + +app.exec() diff --git a/docs/examples/iconify.py b/docs/examples/iconify.py new file mode 100644 index 00000000..1ca07249 --- /dev/null +++ b/docs/examples/iconify.py @@ -0,0 +1,13 @@ +from qtpy.QtCore import QSize +from qtpy.QtWidgets import QApplication, QPushButton + +from superqt import QIconifyIcon + +app = QApplication([]) + +btn = QPushButton() +btn.setIcon(QIconifyIcon("fluent-emoji-flat:alarm-clock")) +btn.setIconSize(QSize(60, 60)) +btn.show() + +app.exec() diff --git a/docs/examples/qcollapsible.py b/docs/examples/qcollapsible.py new file mode 100644 index 00000000..87e1bb7a --- /dev/null +++ b/docs/examples/qcollapsible.py @@ -0,0 +1,14 @@ +from qtpy.QtWidgets import QApplication, QLabel, QPushButton + +from superqt import QCollapsible + +app = QApplication([]) + +collapsible = QCollapsible("Advanced analysis") +collapsible.addWidget(QLabel("This is the inside of the collapsible frame")) +for i in range(4): + collapsible.addWidget(QPushButton(f"Content button {i + 1}")) + +collapsible.expand(animate=False) +collapsible.show() +app.exec() diff --git a/docs/examples/qcolorcombobox.py b/docs/examples/qcolorcombobox.py new file mode 100644 index 00000000..fda61603 --- /dev/null +++ b/docs/examples/qcolorcombobox.py @@ -0,0 +1,17 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QColorComboBox + +app = QApplication([]) + +colors = QColorComboBox() +colors.addColors(["red", "green", "blue"]) + +# show an "Add Color" item that opens a QColorDialog when clicked +colors.setUserColorsAllowed(True) + +# emits a QColor when changed +colors.currentColorChanged.connect(print) +colors.show() + +app.exec() diff --git a/docs/examples/qcolormap.py b/docs/examples/qcolormap.py new file mode 100644 index 00000000..6c6754f4 --- /dev/null +++ b/docs/examples/qcolormap.py @@ -0,0 +1,18 @@ +from cmap import Colormap +from qtpy.QtWidgets import QApplication + +from superqt import QColormapComboBox + +app = QApplication([]) + +cmap_combo = QColormapComboBox() +# see note above about colormap-like objects +# as names from the cmap catalog +cmap_combo.addColormaps(["viridis", "plasma", "magma", "gray"]) +# as a sequence of colors, linearly interpolated +cmap_combo.addColormap(("#0f0", "slateblue", "#F3A003A0")) +# as a `cmap.Colormap` instance with custom name: +cmap_combo.addColormap(Colormap(("green", "white", "orange"), name="MyMap")) + +cmap_combo.show() +app.exec() diff --git a/docs/examples/qdoublerangeslider.py b/docs/examples/qdoublerangeslider.py new file mode 100644 index 00000000..c803763a --- /dev/null +++ b/docs/examples/qdoublerangeslider.py @@ -0,0 +1,13 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication + +from superqt import QDoubleRangeSlider + +app = QApplication([]) + +slider = QDoubleRangeSlider(Qt.Orientation.Horizontal) +slider.setRange(0, 1) +slider.setValue((0.2, 0.8)) +slider.show() + +app.exec() diff --git a/docs/examples/qdoubleslider.py b/docs/examples/qdoubleslider.py new file mode 100644 index 00000000..369eec25 --- /dev/null +++ b/docs/examples/qdoubleslider.py @@ -0,0 +1,13 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication + +from superqt import QDoubleSlider + +app = QApplication([]) + +slider = QDoubleSlider(Qt.Orientation.Horizontal) +slider.setRange(0, 1) +slider.setValue(0.5) +slider.show() + +app.exec() diff --git a/docs/examples/qelidinglabel.py b/docs/examples/qelidinglabel.py new file mode 100644 index 00000000..763a4eee --- /dev/null +++ b/docs/examples/qelidinglabel.py @@ -0,0 +1,15 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QElidingLabel + +app = QApplication([]) + +widget = QElidingLabel( + "a skj skjfskfj sdlf sdfl sdlfk jsdf sdlkf jdsf dslfksdl sdlfk sdf sdl " + "fjsdlf kjsdlfk laskdfsal as lsdfjdsl kfjdslf asfd dslkjfldskf sdlkfj" +) +widget.setWordWrap(True) +widget.resize(300, 20) +widget.show() + +app.exec() diff --git a/docs/examples/qenumcombobox.py b/docs/examples/qenumcombobox.py new file mode 100644 index 00000000..4ebe5d0f --- /dev/null +++ b/docs/examples/qenumcombobox.py @@ -0,0 +1,20 @@ +from enum import Enum + +from qtpy.QtWidgets import QApplication + +from superqt import QEnumComboBox + + +class SampleEnum(Enum): + first = 1 + second = 2 + third = 3 + + +app = QApplication([]) + +combo = QEnumComboBox() +combo.setEnumClass(SampleEnum) +combo.show() + +app.exec() diff --git a/docs/examples/qflowlayout.py b/docs/examples/qflowlayout.py new file mode 100644 index 00000000..8423aa2d --- /dev/null +++ b/docs/examples/qflowlayout.py @@ -0,0 +1,19 @@ +from qtpy.QtWidgets import QApplication, QPushButton, QWidget + +from superqt import QFlowLayout + +app = QApplication([]) + +wdg = QWidget() + +layout = QFlowLayout(wdg) +layout.addWidget(QPushButton("Short")) +layout.addWidget(QPushButton("Longer")) +layout.addWidget(QPushButton("Different text")) +layout.addWidget(QPushButton("More text")) +layout.addWidget(QPushButton("Even longer button text")) + +wdg.setWindowTitle("Flow Layout") +wdg.show() + +app.exec() diff --git a/docs/examples/qlabeleddoublerangeslider.py b/docs/examples/qlabeleddoublerangeslider.py new file mode 100644 index 00000000..6ac79c62 --- /dev/null +++ b/docs/examples/qlabeleddoublerangeslider.py @@ -0,0 +1,13 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication + +from superqt import QLabeledDoubleRangeSlider + +app = QApplication([]) + +slider = QLabeledDoubleRangeSlider(Qt.Orientation.Horizontal) +slider.setRange(0, 1) +slider.setValue((0.2, 0.8)) +slider.show() + +app.exec() diff --git a/docs/examples/qlabeleddoubleslider.py b/docs/examples/qlabeleddoubleslider.py new file mode 100644 index 00000000..d40c015d --- /dev/null +++ b/docs/examples/qlabeleddoubleslider.py @@ -0,0 +1,13 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication + +from superqt import QLabeledDoubleSlider + +app = QApplication([]) + +slider = QLabeledDoubleSlider(Qt.Orientation.Horizontal) +slider.setRange(0, 2.5) +slider.setValue(1.3) +slider.show() + +app.exec() diff --git a/docs/examples/qlabeledrangeslider.py b/docs/examples/qlabeledrangeslider.py new file mode 100644 index 00000000..2df962e9 --- /dev/null +++ b/docs/examples/qlabeledrangeslider.py @@ -0,0 +1,12 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication + +from superqt import QLabeledRangeSlider + +app = QApplication([]) + +slider = QLabeledRangeSlider(Qt.Orientation.Horizontal) +slider.setValue((20, 80)) +slider.show() + +app.exec() diff --git a/docs/examples/qlabeledslider.py b/docs/examples/qlabeledslider.py new file mode 100644 index 00000000..d39d4dd6 --- /dev/null +++ b/docs/examples/qlabeledslider.py @@ -0,0 +1,12 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication + +from superqt import QLabeledSlider + +app = QApplication([]) + +slider = QLabeledSlider(Qt.Orientation.Horizontal) +slider.setValue(42) +slider.show() + +app.exec() diff --git a/docs/examples/qlargeintspinbox.py b/docs/examples/qlargeintspinbox.py new file mode 100644 index 00000000..71320ce9 --- /dev/null +++ b/docs/examples/qlargeintspinbox.py @@ -0,0 +1,12 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QLargeIntSpinBox + +app = QApplication([]) + +slider = QLargeIntSpinBox() +slider.setRange(0, 4.53e8) +slider.setValue(4.53e8) +slider.show() + +app.exec() diff --git a/docs/examples/qquantity.py b/docs/examples/qquantity.py new file mode 100644 index 00000000..f00d937f --- /dev/null +++ b/docs/examples/qquantity.py @@ -0,0 +1,9 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QQuantity + +app = QApplication([]) +w = QQuantity("1m") +w.show() + +app.exec() diff --git a/docs/examples/qrangeslider.py b/docs/examples/qrangeslider.py new file mode 100644 index 00000000..c733f5bb --- /dev/null +++ b/docs/examples/qrangeslider.py @@ -0,0 +1,12 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication + +from superqt import QRangeSlider + +app = QApplication([]) + +slider = QRangeSlider(Qt.Orientation.Horizontal) +slider.setValue((20, 80)) +slider.show() + +app.exec() diff --git a/docs/examples/qsearchablecombobox.py b/docs/examples/qsearchablecombobox.py new file mode 100644 index 00000000..9ebeb299 --- /dev/null +++ b/docs/examples/qsearchablecombobox.py @@ -0,0 +1,11 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QSearchableComboBox + +app = QApplication([]) + +combo = QSearchableComboBox() +combo.addItems(["foo", "bar", "baz", "foobar", "foobaz", "barbaz"]) +combo.show() + +app.exec() diff --git a/docs/examples/qsearchablelistwidget.py b/docs/examples/qsearchablelistwidget.py new file mode 100644 index 00000000..336ab967 --- /dev/null +++ b/docs/examples/qsearchablelistwidget.py @@ -0,0 +1,11 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QSearchableListWidget + +app = QApplication([]) + +slider = QSearchableListWidget() +slider.addItems(["foo", "bar", "baz", "foobar", "foobaz", "barbaz"]) +slider.show() + +app.exec() diff --git a/docs/examples/qsearchabletreewidget.py b/docs/examples/qsearchabletreewidget.py new file mode 100644 index 00000000..3bc2e429 --- /dev/null +++ b/docs/examples/qsearchabletreewidget.py @@ -0,0 +1,21 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QSearchableTreeWidget + +app = QApplication([]) + +data = { + "none": None, + "str": "test", + "int": 42, + "list": [2, 3, 5], + "dict": { + "float": 0.5, + "tuple": (22, 99), + "bool": False, + }, +} +tree = QSearchableTreeWidget.fromData(data) +tree.show() + +app.exec() diff --git a/docs/examples/qtoggleswitch.py b/docs/examples/qtoggleswitch.py new file mode 100644 index 00000000..e77294d9 --- /dev/null +++ b/docs/examples/qtoggleswitch.py @@ -0,0 +1,10 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QToggleSwitch + +app = QApplication([]) + +switch = QToggleSwitch() +switch.show() + +app.exec() diff --git a/docs/examples/showcase.py b/docs/examples/showcase.py new file mode 100644 index 00000000..f0dfe65b --- /dev/null +++ b/docs/examples/showcase.py @@ -0,0 +1,38 @@ +from qtpy.QtCore import Qt +from qtpy.QtWidgets import QApplication, QFormLayout, QWidget + +from superqt import ( + QColormapComboBox, + QLabeledDoubleSlider, + QLabeledRangeSlider, + QSearchableComboBox, + QToggleSwitch, +) + +app = QApplication([]) + +panel = QWidget() +form = QFormLayout(panel) + +channel = QSearchableComboBox() +channel.addItems(["DAPI", "GFP", "mCherry", "Cy5", "Brightfield"]) +form.addRow("Channel", channel) + +limits = QLabeledRangeSlider(Qt.Orientation.Horizontal) +limits.setRange(0, 255) +limits.setValue((30, 200)) +form.addRow("Contrast", limits) + +cmap = QColormapComboBox() +cmap.addColormaps(["viridis", "magma", "inferno", "gray"]) +form.addRow("Colormap", cmap) + +form.addRow("Auto-scale", QToggleSwitch()) + +gamma = QLabeledDoubleSlider(Qt.Orientation.Horizontal) +gamma.setRange(0.1, 3) +gamma.setValue(1) +form.addRow("Gamma", gamma) + +panel.show() +app.exec() diff --git a/docs/images/favicon.svg b/docs/images/favicon.svg new file mode 100644 index 00000000..38906037 --- /dev/null +++ b/docs/images/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/index.md b/docs/index.md index 96573d72..786592d3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,12 +1,50 @@ +--- +hide: + - navigation + - toc +--- + +
+
+ # superqt -## ![tiny](https://user-images.githubusercontent.com/1609449/120636353-8c3f3800-c43b-11eb-8732-a14dec578897.png) "missing" widgets and components for PyQt/PySide +

"Missing" widgets and components for PyQt and PySide.

This repository aims to provide high-quality community-contributed Qt widgets and components for [PyQt](https://riverbankcomputing.com/software/pyqt/) & [PySide](https://www.qt.io/qt-for-python) that are not provided in the native QtWidgets module. +[Widgets](widgets/index.md){ .md-button .md-button--primary } +[Utilities](utilities/index.md){ .md-button } + +
+ +{{ show_widget("showcase") }} + +
+ +## Installation + +=== "pip" + + ```bash + pip install superqt + ``` + +=== "uv" + + ```bash + uv add superqt + ``` + +=== "conda" + + ```bash + conda install -c conda-forge superqt + ``` + Components are tested on: - macOS, Windows, & Linux @@ -14,16 +52,20 @@ Components are tested on: - PyQt5 (5.11 and above) & PyQt6 - PySide6 -## Installation +## Widgets -```bash -pip install superqt -``` + -```bash -conda install -c conda-forge superqt -``` +[All widgets](widgets/index.md){ .md-button } -## Usage +## Utilities -See the [Widgets](./widgets/index.md) and [Utilities](./utilities/index.md) pages for features offered by superqt. +See the [Utilities](utilities/index.md) page for font icons, threading tools, +throttling and debouncing, and more. diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css new file mode 100644 index 00000000..180b71ad --- /dev/null +++ b/docs/stylesheets/extra.css @@ -0,0 +1,185 @@ +/* --------------------------------------------------------------------------- + Colors. Keep --sq-accent in sync with `Highlight` in docs/_media.py, so the + widgets in screenshots match the site. +--------------------------------------------------------------------------- */ + +:root, +[data-md-color-scheme="default"] { + --sq-accent: #4d5bd8; + --md-primary-fg-color: #4d5bd8; + --md-primary-fg-color--light: #7782e8; + --md-primary-fg-color--dark: #3a46b0; + --md-accent-fg-color: #3a46b0; + --md-accent-fg-color--transparent: #4d5bd81a; + --sq-figure-bg: #f3f4f7; /* `Window` in light screenshots */ + --sq-figure-border: #e1e4ea; + --sq-figure-shadow: 0 1px 2px #0000000d, 0 4px 16px #0000000a; +} + +[data-md-color-scheme="slate"] { + --sq-accent: #6f7cf2; + --md-primary-fg-color: #8f9aff; + --md-primary-fg-color--light: #b3baff; + --md-primary-fg-color--dark: #6f7cf2; + --md-accent-fg-color: #b3baff; + --md-accent-fg-color--transparent: #8f9aff1a; + --md-typeset-a-color: #8f9aff; + --sq-figure-bg: #1b1e25; /* `Window` in dark screenshots */ + --sq-figure-border: #2b2f38; + --sq-figure-shadow: 0 1px 2px #00000040, 0 6px 20px #00000033; +} + +/* --------------------------------------------------------------------------- + Widget screenshots: {{ show_widget() }} +--------------------------------------------------------------------------- */ + +.md-typeset figure.sq-demo { + margin: 1.6em auto; +} + +.md-typeset figure.sq-demo img { + max-width: 100%; + height: auto; + border: 1px solid var(--sq-figure-border); + border-radius: 10px; + background: var(--sq-figure-bg); + box-shadow: var(--sq-figure-shadow); +} + +/* --------------------------------------------------------------------------- + Gallery (home page and section index pages) +--------------------------------------------------------------------------- */ + +.md-typeset .sq-gallery { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); + gap: 0.8rem; + margin: 1em 0 2em; +} + +.md-typeset .sq-gallery > p { + display: contents; /* the cards are the grid items */ +} + +.md-typeset .sq-card { + display: flex; + flex-direction: column; + overflow: hidden; + border: 1px solid var(--sq-figure-border); + border-radius: 10px; + color: inherit; + text-decoration: none; + transition: + border-color 150ms, + box-shadow 150ms, + transform 150ms; +} + +.md-typeset .sq-card:hover, +.md-typeset .sq-card:focus-visible { + color: inherit; + border-color: var(--md-primary-fg-color); + box-shadow: var(--sq-figure-shadow); + transform: translateY(-1px); +} + +.md-typeset .sq-card__thumb { + display: flex; + align-items: center; + justify-content: center; + height: 6.5rem; + padding: 0.4rem; + background: var(--sq-figure-bg); + border-bottom: 1px solid var(--sq-figure-border); +} + +.md-typeset .sq-card__thumb img { + max-width: 100%; + max-height: 100%; + width: auto; + height: auto; + object-fit: contain; +} + +.md-typeset .sq-card__body { + padding: 0.55rem 0.75rem 0.7rem; +} + +.md-typeset .sq-card__body strong { + display: block; + font-family: var(--md-code-font-family); + font-size: 0.72rem; + font-weight: 600; + color: var(--md-typeset-a-color); +} + +.md-typeset .sq-card * { + text-decoration: none; +} + +.md-typeset .sq-card__body code { + color: inherit; +} + +.md-typeset .sq-card__body span { + display: block; + margin-top: 0.15rem; + font-size: 0.66rem; + line-height: 1.45; + color: var(--md-default-fg-color--light); +} + +/* --------------------------------------------------------------------------- + Home page +--------------------------------------------------------------------------- */ + +.md-typeset .sq-hero { + margin: 0.5rem 0 2rem; +} + +@media screen and (min-width: 60em) { + .md-typeset .sq-hero { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 2.5rem; + align-items: center; + } + + .md-typeset .sq-hero figure.sq-demo { + margin: 0; + } +} + +.md-typeset .sq-hero h1 { + margin-bottom: 0.4rem; + font-weight: 700; + letter-spacing: -0.02em; +} + +.md-typeset .sq-hero .sq-lead { + margin-top: 0; + font-size: 0.95rem; + line-height: 1.55; + color: var(--md-default-fg-color--light); +} + +.md-typeset .sq-hero .md-button { + margin: 0.2rem 0.4rem 0.2rem 0; +} + +/* --------------------------------------------------------------------------- + API reference (mkdocstrings) +--------------------------------------------------------------------------- */ + +.md-typeset .doc-heading code { + font-weight: 600; +} + +.md-typeset .doc-contents:not(.first) { + padding-left: 0.9rem; + border-left: 0.05rem solid var(--md-typeset-table-color); +} + +.md-typeset .doc-section-title { + font-weight: 600; +} diff --git a/docs/utilities/code_syntax_highlight.md b/docs/utilities/code_syntax_highlight.md index 225a3eba..633b01a3 100644 --- a/docs/utilities/code_syntax_highlight.md +++ b/docs/utilities/code_syntax_highlight.md @@ -11,42 +11,12 @@ List of available styles are available [here](https://pygments.org/styles/). ## Example -```python -from qtpy.QtGui import QColor, QPalette -from qtpy.QtWidgets import QApplication, QTextEdit - -from superqt.utils import CodeSyntaxHighlight - -app = QApplication([]) - -text_area = QTextEdit() - -highlight = CodeSyntaxHighlight(text_area.document(), "python", "monokai") - -palette = text_area.palette() -palette.setColor(QPalette.Base, QColor(highlight.background_color)) -text_area.setPalette(palette) -text_area.setText( - """from argparse import ArgumentParser - -def main(): - parser = ArgumentParser() - parser.add_argument("name", help="Your name") - args = parser.parse_args() - print(f"Hello {args.name}") - - -if __name__ == "__main__": - main() -""" -) - -text_area.show() -text_area.resize(400, 200) +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/code_syntax_highlight.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.utils.CodeSyntaxHighlight') }} diff --git a/docs/utilities/fonticon.md b/docs/utilities/fonticon.md index 8652f9e7..027f4793 100644 --- a/docs/utilities/fonticon.md +++ b/docs/utilities/fonticon.md @@ -6,26 +6,14 @@ Icons](https://materialdesignicons.com/). ## Basic Example -```python -from fonticon_fa5 import FA5S - -from qtpy.QtCore import QSize -from qtpy.QtWidgets import QApplication, QPushButton - -from superqt.fonticon import icon, pulse - -app = QApplication([]) - -btn2 = QPushButton() -btn2.setIcon(icon(FA5S.smile, color="blue")) -btn2.setIconSize(QSize(225, 225)) -btn2.show() +{{ show_widget() }} -app.exec() +```python +--8<-- +examples/fonticon.py +--8<-- ``` -{{ show_widget(225) }} - ## Font Icon plugins Ready-made fonticon packs are available as plugins. @@ -36,7 +24,6 @@ search interface is to use glyphsearch: If a font library you'd like to use is unavailable as a superqt plugin, please [open a feature request](https://github.com/pyapp-kit/superqt/issues/new/choose) - ### Font Awesome 6 Browse available icons at @@ -87,24 +74,28 @@ entry point to register themselves with superqt. See [`fonticon-cookiecutter`](h ## API ::: superqt.fonticon.icon -options: -heading_level: 3 + options: + heading_level: 3 ::: superqt.fonticon.setTextIcon -options: -heading_level: 3 + options: + heading_level: 3 ::: superqt.fonticon.font -options: -heading_level: 3 + options: + heading_level: 3 ::: superqt.fonticon.IconOpts -options: -heading_level: 3 + options: + heading_level: 3 ::: superqt.fonticon.addFont -options: -heading_level: 3 + options: + heading_level: 3 + +::: superqt.fonticon.IconFont + options: + heading_level: 3 ## Animations @@ -112,13 +103,13 @@ the `animation` parameter to `icon()` accepts a subclass of `Animation` that will be ::: superqt.fonticon.Animation -options: -heading_level: 3 + options: + heading_level: 3 ::: superqt.fonticon.pulse -options: -heading_level: 3 + options: + heading_level: 3 ::: superqt.fonticon.spin -options: -heading_level: 3 + options: + heading_level: 3 diff --git a/docs/utilities/iconify.md b/docs/utilities/iconify.md index 1b9ae29c..5cf7b627 100644 --- a/docs/utilities/iconify.md +++ b/docs/utilities/iconify.md @@ -13,24 +13,14 @@ icon: `QIconifyIcon("bi:bell")`. ## Basic Example -```python -from qtpy.QtCore import QSize -from qtpy.QtWidgets import QApplication, QPushButton - -from superqt import QIconifyIcon - -app = QApplication([]) +{{ show_widget() }} -btn = QPushButton() -btn.setIcon(QIconifyIcon("fluent-emoji-flat:alarm-clock")) -btn.setIconSize(QSize(60, 60)) -btn.show() - -app.exec() +```python +--8<-- +examples/iconify.py +--8<-- ``` -{{ show_widget(225) }} - ::: superqt.QIconifyIcon options: heading_level: 3 diff --git a/docs/widgets/colormap_catalog.md b/docs/widgets/colormap_catalog.md index 48da710b..d97fbf8b 100644 --- a/docs/widgets/colormap_catalog.md +++ b/docs/widgets/colormap_catalog.md @@ -16,20 +16,12 @@ Searchable `QComboBox` variant that contains the You can limit the colormaps shown by setting the `categories` or `interpolation` keyword arguments. -```python -from qtpy.QtWidgets import QApplication - -from superqt.cmap import CmapCatalogComboBox - -app = QApplication([]) +{{ show_widget() }} -catalog_combo = CmapCatalogComboBox(interpolation="linear") -catalog_combo.setCurrentText("viridis") -catalog_combo.show() - -app.exec() +```python +--8<-- +examples/colormap_catalog.py +--8<-- ``` -{{ show_widget(130) }} - {{ show_members('superqt.cmap.CmapCatalogComboBox') }} diff --git a/docs/widgets/index.md b/docs/widgets/index.md index 6bc2412f..69a7ee51 100644 --- a/docs/widgets/index.md +++ b/docs/widgets/index.md @@ -1,37 +1,58 @@ +--- +hide: + - toc +--- + # Widgets The following are QWidget subclasses: -## Sliders and Numerical Inputs - -| Widget | Description | -| ----------- | --------------------- | -| [`QDoubleRangeSlider`](./qdoublerangeslider.md) | Multi-handle slider for float values | -| [`QDoubleSlider`](./qdoubleslider.md) | Slider for float values | -| [`QLabeledDoubleRangeSlider`](./qlabeleddoublerangeslider.md) | `QDoubleRangeSlider` variant with editable labels for each handle | -| [`QLabeledDoubleSlider`](./qlabeleddoubleslider.md) | `QSlider` for float values with editable `QSpinBox` with the current value | -| [`QLabeledRangeSlider`](./qlabeledrangeslider.md) | `QRangeSlider` variant, with editable labels for each handle | -| [`QLabeledSlider`](./qlabeledslider.md) | `QSlider` with editable `QSpinBox` that shows the current value | -| [`QLargeIntSpinBox`](./qlargeintspinbox.md) | `QSpinbox` that accepts arbitrarily large integers | -| [`QRangeSlider`](./qrangeslider.md) | Multi-handle slider | -| [`QQuantity`](./qquantity.md) | Pint-backed quantity widget (magnitude combined with unit dropdown) | - -## Labels and categorical inputs - -| Widget | Description | -| ----------- | --------------------- | -| [`QElidingLabel`](./qelidinglabel.md) | A `QLabel` variant that will elide text (add `…`) to fit width. | -| [`QEnumComboBox`](./qenumcombobox.md) | `QComboBox` that populates the combobox from a python `Enum` | -| [`QSearchableComboBox`](./qsearchablecombobox.md) | `QComboBox` variant that filters available options based on text input | -| [`QSearchableListWidget`](./qsearchablelistwidget.md) | `QListWidget` variant with search field that filters available options | -| [`QSearchableTreeWidget`](./qsearchabletreewidget.md) | `QTreeWidget` variant with search field that filters available options | -| [`QColorComboBox`](./qcolorcombobox.md) | `QComboBox` to select from a specified set of colors | -| [`QColormapComboBox`](./qcolormap.md) | `QComboBox` to select from a specified set of colormaps. | -| [`QToggleSwitch`](./qtoggleswitch.md) | `QAbstractButton` that represents a boolean value with a toggle switch. | - -## Frames and containers - -| Widget | Description | -| ----------- | --------------------- | -| [`QCollapsible`](./qcollapsible.md) | A collapsible widget to hide and unhide child widgets. | -| [`QFlowLayout`](./qflowlayout.md) | A layout that rearranges items based on parent width. | +## Sliders + + + +## Numeric inputs + + + +## Combo boxes + + + +## Lists and trees + + + +## Text and buttons + + + +## Containers and layouts + + diff --git a/docs/widgets/qcollapsible.md b/docs/widgets/qcollapsible.md index 9e52fc25..6e21e1d6 100644 --- a/docs/widgets/qcollapsible.md +++ b/docs/widgets/qcollapsible.md @@ -2,23 +2,12 @@ Collapsible `QFrame` that can be expanded or collapsed by clicking on the header. -```python -from qtpy.QtWidgets import QApplication, QLabel, QPushButton - -from superqt import QCollapsible - -app = QApplication([]) +{{ show_widget() }} -collapsible = QCollapsible("Advanced analysis") -collapsible.addWidget(QLabel("This is the inside of the collapsible frame")) -for i in range(10): - collapsible.addWidget(QPushButton(f"Content button {i + 1}")) - -collapsible.expand(animate=False) -collapsible.show() -app.exec_() +```python +--8<-- +examples/qcollapsible.py +--8<-- ``` -{{ show_widget(350) }} - {{ show_members('superqt.QCollapsible') }} diff --git a/docs/widgets/qcolorcombobox.md b/docs/widgets/qcolorcombobox.md index 0744d4b0..a4388151 100644 --- a/docs/widgets/qcolorcombobox.md +++ b/docs/widgets/qcolorcombobox.md @@ -2,26 +2,12 @@ `QComboBox` designed to select from a specific set of colors. -```python -from qtpy.QtWidgets import QApplication - -from superqt import QColorComboBox - -app = QApplication([]) - -colors = QColorComboBox() -colors.addColors(["red", "green", "blue"]) +{{ show_widget() }} -# show an "Add Color" item that opens a QColorDialog when clicked -colors.setUserColorsAllowed(True) - -# emits a QColor when changed -colors.currentColorChanged.connect(print) -colors.show() - -app.exec_() +```python +--8<-- +examples/qcolorcombobox.py +--8<-- ``` -{{ show_widget(100) }} - {{ show_members('superqt.QColorComboBox') }} diff --git a/docs/widgets/qcolormap.md b/docs/widgets/qcolormap.md index f75c976d..dec62996 100644 --- a/docs/widgets/qcolormap.md +++ b/docs/widgets/qcolormap.md @@ -20,29 +20,14 @@ all ColormapLike types](https://cmap-docs.readthedocs.io/en/latest/colormaps/#co ### Example -```python -from cmap import Colormap -from qtpy.QtWidgets import QApplication - -from superqt import QColormapComboBox - -app = QApplication([]) +{{ show_widget() }} -cmap_combo = QColormapComboBox() -# see note above about colormap-like objects -# as names from the cmap catalog -cmap_combo.addColormaps(["viridis", "plasma", "magma", "gray"]) -# as a sequence of colors, linearly interpolated -cmap_combo.addColormap(("#0f0", "slateblue", "#F3A003A0")) -# as a `cmap.Colormap` instance with custom name: -cmap_combo.addColormap(Colormap(("green", "white", "orange"), name="MyMap")) - -cmap_combo.show() -app.exec() +```python +--8<-- +examples/qcolormap.py +--8<-- ``` -{{ show_widget(200) }} - ### Style Customization Note that both the LineEdit and the dropdown can be styled to have the colormap diff --git a/docs/widgets/qdoublerangeslider.md b/docs/widgets/qdoublerangeslider.md index 128ee67c..281b4ae5 100644 --- a/docs/widgets/qdoublerangeslider.md +++ b/docs/widgets/qdoublerangeslider.md @@ -2,22 +2,12 @@ Float variant of [`QRangeSlider`](qrangeslider.md). (see that page for more details). -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QDoubleRangeSlider - -app = QApplication([]) - -slider = QDoubleRangeSlider(Qt.Orientation.Horizontal) -slider.setRange(0, 1) -slider.setValue((0.2, 0.8)) -slider.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qdoublerangeslider.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QDoubleRangeSlider') }} diff --git a/docs/widgets/qdoubleslider.md b/docs/widgets/qdoubleslider.md index 137a3389..dc1bde27 100644 --- a/docs/widgets/qdoubleslider.md +++ b/docs/widgets/qdoubleslider.md @@ -2,22 +2,12 @@ `QSlider` variant that accepts floating point values. -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QDoubleSlider - -app = QApplication([]) - -slider = QDoubleSlider(Qt.Orientation.Horizontal) -slider.setRange(0, 1) -slider.setValue(0.5) -slider.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qdoubleslider.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QDoubleSlider') }} diff --git a/docs/widgets/qelidinglabel.md b/docs/widgets/qelidinglabel.md index 0bc42e46..392f87c4 100644 --- a/docs/widgets/qelidinglabel.md +++ b/docs/widgets/qelidinglabel.md @@ -3,24 +3,12 @@ `QLabel` variant that will elide text (i.e. add an ellipsis) if it is too long to fit in the available space. -```python -from qtpy.QtWidgets import QApplication - -from superqt import QElidingLabel - -app = QApplication([]) +{{ show_widget() }} -widget = QElidingLabel( - "a skj skjfskfj sdlf sdfl sdlfk jsdf sdlkf jdsf dslfksdl sdlfk sdf sdl " - "fjsdlf kjsdlfk laskdfsal as lsdfjdsl kfjdslf asfd dslkjfldskf sdlkfj" -) -widget.setWordWrap(True) -widget.resize(300, 20) -widget.show() - -app.exec_() +```python +--8<-- +examples/qelidinglabel.py +--8<-- ``` -{{ show_widget(300) }} - {{ show_members('superqt.QElidingLabel') }} diff --git a/docs/widgets/qenumcombobox.md b/docs/widgets/qenumcombobox.md index 28c20779..1d34a9f8 100644 --- a/docs/widgets/qenumcombobox.md +++ b/docs/widgets/qenumcombobox.md @@ -12,30 +12,14 @@ analogous to `currentIndexChanged` and `currentTextChanged`. Method like `insertItem` and `addItem` are blocked and try of its usage will end with `RuntimeError` -```python -from enum import Enum - -from qtpy.QtWidgets import QApplication -from superqt import QEnumComboBox - - -class SampleEnum(Enum): - first = 1 - second = 2 - third = 3 - - -app = QApplication([]) - -combo = QEnumComboBox() -combo.setEnumClass(SampleEnum) -combo.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qenumcombobox.py +--8<-- ``` -{{ show_widget() }} - Another option is to use optional `enum_class` argument of constructor and change ```python diff --git a/docs/widgets/qflowlayout.md b/docs/widgets/qflowlayout.md index 74e5f88c..c126135c 100644 --- a/docs/widgets/qflowlayout.md +++ b/docs/widgets/qflowlayout.md @@ -2,28 +2,12 @@ QLayout that rearranges items based on parent width. -```python -from qtpy.QtWidgets import QApplication, QPushButton, QWidget - -from superqt import QFlowLayout - -app = QApplication([]) - -wdg = QWidget() +{{ show_widget() }} -layout = QFlowLayout(wdg) -layout.addWidget(QPushButton("Short")) -layout.addWidget(QPushButton("Longer")) -layout.addWidget(QPushButton("Different text")) -layout.addWidget(QPushButton("More text")) -layout.addWidget(QPushButton("Even longer button text")) - -wdg.setWindowTitle("Flow Layout") -wdg.show() - -app.exec() +```python +--8<-- +examples/qflowlayout.py +--8<-- ``` -{{ show_widget(350) }} - {{ show_members('superqt.QFlowLayout') }} diff --git a/docs/widgets/qlabeleddoublerangeslider.md b/docs/widgets/qlabeleddoublerangeslider.md index 0829c527..6dc3a15d 100644 --- a/docs/widgets/qlabeleddoublerangeslider.md +++ b/docs/widgets/qlabeleddoublerangeslider.md @@ -2,22 +2,12 @@ Labeled Float variant of [`QRangeSlider`](qrangeslider.md). (see that page for more details). -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QLabeledDoubleRangeSlider - -app = QApplication([]) - -slider = QLabeledDoubleRangeSlider(Qt.Orientation.Horizontal) -slider.setRange(0, 1) -slider.setValue((0.2, 0.8)) -slider.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qlabeleddoublerangeslider.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QLabeledDoubleRangeSlider') }} diff --git a/docs/widgets/qlabeleddoubleslider.md b/docs/widgets/qlabeleddoubleslider.md index 29a17ce8..54a7ae04 100644 --- a/docs/widgets/qlabeleddoubleslider.md +++ b/docs/widgets/qlabeleddoubleslider.md @@ -2,23 +2,12 @@ [`QDoubleSlider`](./qdoubleslider.md) variant that shows an editable (SpinBox) label next to the slider. +{{ show_widget() }} ```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QLabeledDoubleSlider - -app = QApplication([]) - -slider = QLabeledDoubleSlider(Qt.Orientation.Horizontal) -slider.setRange(0, 2.5) -slider.setValue(1.3) -slider.show() - -app.exec_() +--8<-- +examples/qlabeleddoubleslider.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QLabeledDoubleSlider') }} diff --git a/docs/widgets/qlabeledrangeslider.md b/docs/widgets/qlabeledrangeslider.md index 10012b2d..006b1003 100644 --- a/docs/widgets/qlabeledrangeslider.md +++ b/docs/widgets/qlabeledrangeslider.md @@ -2,23 +2,14 @@ Labeled variant of [`QRangeSlider`](qrangeslider.md). (see that page for more details). -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QLabeledRangeSlider - -app = QApplication([]) - -slider = QLabeledRangeSlider(Qt.Orientation.Horizontal) -slider.setValue((20, 80)) -slider.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qlabeledrangeslider.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QLabeledRangeSlider') }} ---- diff --git a/docs/widgets/qlabeledslider.md b/docs/widgets/qlabeledslider.md index 66cb2de3..b3527f12 100644 --- a/docs/widgets/qlabeledslider.md +++ b/docs/widgets/qlabeledslider.md @@ -2,21 +2,12 @@ `QSlider` variant that shows an editable (SpinBox) label next to the slider. -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QLabeledSlider - -app = QApplication([]) - -slider = QLabeledSlider(Qt.Orientation.Horizontal) -slider.setValue(42) -slider.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qlabeledslider.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QLabeledSlider') }} diff --git a/docs/widgets/qlargeintspinbox.md b/docs/widgets/qlargeintspinbox.md index 69f0ee4f..0c4e0ed8 100644 --- a/docs/widgets/qlargeintspinbox.md +++ b/docs/widgets/qlargeintspinbox.md @@ -2,22 +2,12 @@ `QSpinBox` variant that allows to enter large integers, without overflow. -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QLargeIntSpinBox - -app = QApplication([]) +{{ show_widget() }} -slider = QLargeIntSpinBox() -slider.setRange(0, 4.53e8) -slider.setValue(4.53e8) -slider.show() - -app.exec_() +```python +--8<-- +examples/qlargeintspinbox.py +--8<-- ``` -{{ show_widget(150) }} - {{ show_members('superqt.QLargeIntSpinBox') }} diff --git a/docs/widgets/qquantity.md b/docs/widgets/qquantity.md index ba709a23..124dff0d 100644 --- a/docs/widgets/qquantity.md +++ b/docs/widgets/qquantity.md @@ -16,16 +16,12 @@ A widget that allows the user to edit a quantity (a magnitude associated with a pip install superqt[quantity] ``` -```python -from qtpy.QtWidgets import QApplication - -from superqt import QQuantity - -app = QApplication([]) -w = QQuantity("1m") -w.show() +{{ show_widget() }} -app.exec() +```python +--8<-- +examples/qquantity.py +--8<-- ``` !!! note @@ -34,6 +30,4 @@ app.exec() `1/second`. However, compound units, e.g. `meter/second`, `Newton`, etc., are not currently supported. -{{ show_widget(150) }} - {{ show_members('superqt.QQuantity') }} diff --git a/docs/widgets/qrangeslider.md b/docs/widgets/qrangeslider.md index 0babaa95..6d4a5ced 100644 --- a/docs/widgets/qrangeslider.md +++ b/docs/widgets/qrangeslider.md @@ -3,23 +3,14 @@ A multi-handle slider widget than can be used to select a range of values. -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QRangeSlider - -app = QApplication([]) - -slider = QRangeSlider(Qt.Orientation.Horizontal) -slider.setValue((20, 80)) -slider.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qrangeslider.py +--8<-- ``` -{{ show_widget() }} - - `QRangeSlider` inherits from [`QSlider`](https://doc.qt.io/qt-6/qslider.html) and attempts to match the Qt API as closely as possible - It uses platform-specific styles (for handle, groove, & ticks) but also supports @@ -177,26 +168,23 @@ These options are in addition to the Qt QSlider API, and control the behavior of app.exec_() ``` -#### macOS - -##### Catalina - -![mac10](../images/demo_darwin10.png){ width=580; } +=== "macOS (Big Sur)" -##### Big Sur + ![QRangeSlider on macOS Big Sur](../images/demo_darwin11.png){ width=580 } -![mac11](../images/demo_darwin11.png){ width=580; } +=== "macOS (Catalina)" -#### Windows + ![QRangeSlider on macOS Catalina](../images/demo_darwin10.png){ width=580 } -![window](../images/demo_windows.png) +=== "Windows" -#### Linux + ![QRangeSlider on Windows](../images/demo_windows.png){ width=580 } -![linux](../images/demo_linux.png) +=== "Linux" + ![QRangeSlider on Linux](../images/demo_linux.png){ width=580 } -{{ show_members('superqt.sliders._sliders._GenericRangeSlider') }} +{{ show_members('superqt.QRangeSlider') }} ## Type changes diff --git a/docs/widgets/qsearchablecombobox.md b/docs/widgets/qsearchablecombobox.md index 63fa3254..e87c8f55 100644 --- a/docs/widgets/qsearchablecombobox.md +++ b/docs/widgets/qsearchablecombobox.md @@ -5,21 +5,12 @@ of options by enter part of text. It could be drop in replacement for `QComboBox`. +{{ show_widget() }} ```python -from qtpy.QtWidgets import QApplication - -from superqt import QSearchableComboBox - -app = QApplication([]) - -combo = QSearchableComboBox() -combo.addItems(["foo", "bar", "baz", "foobar", "foobaz", "barbaz"]) -combo.show() - -app.exec_() +--8<-- +examples/qsearchablecombobox.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QSearchableComboBox') }} diff --git a/docs/widgets/qsearchablelistwidget.md b/docs/widgets/qsearchablelistwidget.md index 8277c0f7..36231370 100644 --- a/docs/widgets/qsearchablelistwidget.md +++ b/docs/widgets/qsearchablelistwidget.md @@ -9,20 +9,12 @@ Due to implementation details, this widget it does not inherit directly from satisfy its api. The only limitation is that it cannot be used as argument of [`QListWidgetItem`](https://doc.qt.io/qt-6/qlistwidgetitem.html) constructor. -```python -from qtpy.QtWidgets import QApplication - -from superqt import QSearchableListWidget - -app = QApplication([]) - -slider = QSearchableListWidget() -slider.addItems(["foo", "bar", "baz", "foobar", "foobaz", "barbaz"]) -slider.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qsearchablelistwidget.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QSearchableListWidget') }} diff --git a/docs/widgets/qsearchabletreewidget.md b/docs/widgets/qsearchabletreewidget.md index a95ebc2c..71cec21b 100644 --- a/docs/widgets/qsearchabletreewidget.md +++ b/docs/widgets/qsearchabletreewidget.md @@ -7,31 +7,12 @@ This is intended to be used with a read-only mapping and be conveniently created using `QSearchableTreeWidget.fromData(data)`. If the mapping changes, the easiest way to update this is by calling `setData`. +{{ show_widget() }} ```python -from qtpy.QtWidgets import QApplication - -from superqt import QSearchableTreeWidget - -app = QApplication([]) - -data = { - "none": None, - "str": "test", - "int": 42, - "list": [2, 3, 5], - "dict": { - "float": 0.5, - "tuple": (22, 99), - "bool": False, - }, -} -tree = QSearchableTreeWidget.fromData(data) -tree.show() - -app.exec_() +--8<-- +examples/qsearchabletreewidget.py +--8<-- ``` -{{ show_widget() }} - {{ show_members('superqt.QSearchableTreeWidget') }} diff --git a/docs/widgets/qtoggleswitch.md b/docs/widgets/qtoggleswitch.md index 7b1540e4..264bf0a2 100644 --- a/docs/widgets/qtoggleswitch.md +++ b/docs/widgets/qtoggleswitch.md @@ -6,19 +6,12 @@ that represents a boolean value as a toggle switch. The API is similar to [`QCheckBox`](https://doc.qt.io/qt-6/qcheckbox.html) but with a different visual representation. -```python -from qtpy.QtWidgets import QApplication - -from superqt import QToggleSwitch - -app = QApplication([]) +{{ show_widget() }} -switch = QToggleSwitch() -switch.show() - -app.exec_() +```python +--8<-- +examples/qtoggleswitch.py +--8<-- ``` -{{ show_widget(80) }} - {{ show_members('superqt.QToggleSwitch') }} diff --git a/mkdocs.yml b/mkdocs.yml deleted file mode 100644 index 6d841e53..00000000 --- a/mkdocs.yml +++ /dev/null @@ -1,56 +0,0 @@ -site_name: superqt -site_url: https://github.com/pyapp-kit/superqt -site_description: >- - missing widgets and components for PyQt/PySide -# Repository -repo_name: pyapp-kit/superqt -repo_url: https://github.com/pyapp-kit/superqt - -# Copyright -copyright: Copyright © 2021 - 2022 - -watch: - - src - -theme: - name: material - features: - - navigation.instant - - navigation.indexes - - navigation.expand - # - navigation.tracking - # - navigation.tabs - - search.highlight - - search.suggest - - content.code.copy - -markdown_extensions: - - admonition - - pymdownx.details - - pymdownx.superfences - - tables - - attr_list - - md_in_html - - pymdownx.emoji: - emoji_index: !!python/name:material.extensions.emoji.twemoji - emoji_generator: !!python/name:material.extensions.emoji.to_svg - - toc: - permalink: "#" - - -plugins: - - search - - autorefs - - macros: - module_name: docs/_macros - - mkdocstrings: - handlers: - python: - import: - - https://docs.python.org/3/objects.inv - - https://cmap-docs.readthedocs.io/en/latest/objects.inv - options: - show_source: false - docstring_style: numpy - show_root_toc_entry: True - show_root_heading: True diff --git a/pyproject.toml b/pyproject.toml index f2e0023b..3b2dd3de 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -104,11 +104,10 @@ dev = [ "prek>=0.3.4", ] docs = [ - "mkdocs-macros-plugin ==1.3.7", - "mkdocs-material ==9.5.49", - "mkdocstrings ==0.27.0", - "mkdocstrings-python ==1.13.0", - "superqt[font-fa5, cmap, quantity]", + "mkdocstrings-python>=2.0.11", + "pillow>=11.0", + "superqt[cmap, font-fa5, iconify, pyqt6, quantity]", + "zensical>=0.1.1", ] @@ -154,6 +153,7 @@ ignore = [ "tests/*.py" = ["D", "S101"] "examples/demo_widget.py" = ["E501"] "examples/*.py" = ["B", "D"] +"docs/examples/*.py" = ["D"] # https://docs.astral.sh/ruff/formatter/ [tool.ruff.format] @@ -213,7 +213,7 @@ ignore = [ ".pre-commit-config.yaml", "tests/**/*", "src/superqt/_version.py", - "mkdocs.yml", + "zensical.toml", "docs/**/*", "examples/**/*", "CHANGELOG.md", diff --git a/zensical.toml b/zensical.toml new file mode 100644 index 00000000..38a3b43c --- /dev/null +++ b/zensical.toml @@ -0,0 +1,229 @@ +# https://zensical.org/docs/setup/basics/ +# +# Widget screenshots and animations are rendered before building: +# +# uv run --group docs python docs/_gen_media.py +# uv run --group docs zensical serve + +[project] +site_name = "superqt" +site_description = "Missing widgets and components for PyQt and PySide" +site_url = "https://pyapp-kit.github.io/superqt/" +repo_name = "pyapp-kit/superqt" +repo_url = "https://github.com/pyapp-kit/superqt" +edit_uri = "edit/main/docs/" +copyright = "Copyright © 2021 - 2026 superqt contributors" + +extra_css = ["stylesheets/extra.css"] + +exclude_docs = """ +_*.py +__pycache__/ +examples/ +_generated/manifest.json +""" + +# rebuild when docstrings change +watch = ["src"] + +nav = [ + { "Home" = "index.md" }, + { "Widgets" = [ + "widgets/index.md", + { "Sliders" = [ + "widgets/qrangeslider.md", + "widgets/qlabeledslider.md", + "widgets/qlabeledrangeslider.md", + "widgets/qdoubleslider.md", + "widgets/qdoublerangeslider.md", + "widgets/qlabeleddoubleslider.md", + "widgets/qlabeleddoublerangeslider.md", + ] }, + { "Numeric inputs" = [ + "widgets/qlargeintspinbox.md", + "widgets/qquantity.md", + ] }, + { "Combo boxes" = [ + "widgets/qenumcombobox.md", + "widgets/qsearchablecombobox.md", + "widgets/qcolorcombobox.md", + "widgets/qcolormap.md", + "widgets/colormap_catalog.md", + ] }, + { "Lists and trees" = [ + "widgets/qsearchablelistwidget.md", + "widgets/qsearchabletreewidget.md", + ] }, + { "Text and buttons" = [ + "widgets/qelidinglabel.md", + "widgets/qtoggleswitch.md", + ] }, + { "Containers and layouts" = [ + "widgets/qcollapsible.md", + "widgets/qflowlayout.md", + ] }, + ] }, + { "Utilities" = [ + "utilities/index.md", + { "Icons" = [ + "utilities/fonticon.md", + "utilities/iconify.md", + ] }, + { "Threading" = [ + "utilities/threading.md", + "utilities/thread_decorators.md", + ] }, + { "Signals and events" = [ + "utilities/throttling.md", + "utilities/signal_utils.md", + "utilities/qmessagehandler.md", + "utilities/error_dialog_contexts.md", + ] }, + { "Drawing" = [ + "utilities/code_syntax_highlight.md", + "utilities/cmap.md", + ] }, + ] }, + { "FAQ" = "faq.md" }, +] + +[project.extra] +generator = false + +[[project.extra.social]] +icon = "fontawesome/brands/github" +link = "https://github.com/pyapp-kit/superqt" + +[[project.extra.social]] +icon = "fontawesome/brands/python" +link = "https://pypi.org/project/superqt/" + +# ---------------------------------------------------------------------------- +# Theme + +[project.theme] +variant = "modern" +language = "en" +favicon = "images/favicon.svg" +font.text = "Inter" +font.code = "JetBrains Mono" +features = [ + "content.action.edit", + "content.code.annotate", + "content.code.copy", + "content.code.select", + "content.tabs.link", + "content.tooltips", + "navigation.footer", + "navigation.indexes", + "navigation.instant", + "navigation.instant.prefetch", + "navigation.instant.progress", + "navigation.path", + "navigation.sections", + "navigation.tabs", + "navigation.top", + "navigation.tracking", + "search.highlight", + "toc.follow", +] + +[project.theme.icon] +logo = "lucide/sliders-horizontal" +repo = "fontawesome/brands/github" +edit = "lucide/pencil" + +[[project.theme.palette]] +media = "(prefers-color-scheme)" +toggle.icon = "lucide/sun-moon" +toggle.name = "Switch to light mode" + +[[project.theme.palette]] +media = "(prefers-color-scheme: light)" +scheme = "default" +primary = "custom" +accent = "custom" +toggle.icon = "lucide/sun" +toggle.name = "Switch to dark mode" + +[[project.theme.palette]] +media = "(prefers-color-scheme: dark)" +scheme = "slate" +primary = "custom" +accent = "custom" +toggle.icon = "lucide/moon" +toggle.name = "Switch to system preference" + +# ---------------------------------------------------------------------------- +# Markdown + +[project.markdown_extensions] +abbr = {} +admonition = {} +attr_list = {} +def_list = {} +md_in_html = {} +tables = {} +toc.permalink = true +toc.toc_depth = 4 +pymdownx.betterem = {} +pymdownx.blocks.caption = {} +pymdownx.details = {} +pymdownx.emoji.emoji_generator = "zensical.extensions.emoji.to_svg" +pymdownx.emoji.emoji_index = "zensical.extensions.emoji.twemoji" +pymdownx.highlight.anchor_linenums = true +pymdownx.highlight.line_spans = "__span" +pymdownx.highlight.pygments_lang_class = true +pymdownx.inlinehilite = {} +pymdownx.keys = {} +pymdownx.magiclink = { repo_url_shorthand = true, user = "pyapp-kit", repo = "superqt" } +pymdownx.smartsymbols = {} +pymdownx.snippets = { base_path = ["docs"], check_paths = true } +pymdownx.superfences = {} +pymdownx.tabbed.alternate_style = true +pymdownx.tabbed.combine_header_slug = true + +# link previews in prose, but not on the cards and buttons of index pages +[[project.markdown_extensions."zensical.extensions.preview".configurations]] +sources.exclude = ["index.md", "widgets/index.md", "utilities/index.md"] +targets.include = ["widgets/*", "utilities/*"] + +# ---------------------------------------------------------------------------- +# Plugins + +[project.plugins.search] + +[project.plugins.autorefs] +resolve_closest = true + +[project.plugins.macros] +module_name = "docs/_macros" +include_dir = "docs/_includes" +render_by_default = true +on_error_fail = true +on_undefined = "strict" + +[project.plugins.mkdocstrings.handlers.python] +paths = ["src"] +inventories = [ + "https://docs.python.org/3/objects.inv", + "https://cmap-docs.readthedocs.io/en/latest/objects.inv", +] + +[project.plugins.mkdocstrings.handlers.python.options] +docstring_style = "numpy" +docstring_section_style = "list" +heading_level = 2 +show_root_heading = true +show_root_full_path = false +show_bases = false +show_source = false +show_symbol_type_heading = true +show_symbol_type_toc = true +show_signature_annotations = true +separate_signature = true +signature_crossrefs = true +merge_init_into_class = true +members_order = "source" +filters = ["!^_"] +show_labels = false From a7fee06af146e9cd2dced97ff3d636ed1a5a55ec Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Thu, 12 Nov 2026 20:59:23 +0100 Subject: [PATCH 02/10] ci: build docs on pull requests, deploy to gh-pages from main Renders the screenshots offscreen, builds with `zensical build --strict`, and uploads the site as an artifact; pushes to main deploy it with ghp-import (zensical has no `gh-deploy`). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/docs.yml | 55 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 .github/workflows/docs.yml diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..3017046c --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,55 @@ +name: Docs + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + docs: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.13" + enable-cache: true + cache-dependency-glob: "**/pyproject.toml" + + # system libraries for Qt (screenshots are rendered offscreen) + - uses: pyvista/setup-headless-display-action@v5 + with: + qt: true + + # screenshots use Inter, the same font as the site + - name: Install fonts + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends fonts-inter + + - name: Render screenshots and animations + run: uv run --group docs python docs/_gen_media.py + + - name: Build + run: uv run --group docs zensical build --clean --strict + + - uses: actions/upload-artifact@v7 + with: + name: site + path: site + + # zensical has no gh-deploy; push the built site to the gh-pages branch + - name: Deploy + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + uvx ghp-import --no-jekyll --push --force site From 994e2ebcc3e13a2c9478124484f02a7f945f0e22 Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Thu, 12 Nov 2026 21:11:42 +0100 Subject: [PATCH 03/10] docs: review the prose for accuracy, clarity and completeness Checked each page against the code, and rewrote it in plain language. Fixed statements that were wrong: - the labels of labeled sliders are line edits, not spin boxes - the range slider's setter is `setBarVisible` (not `setBarIsVisible`), and the mouse wheel moves all of its handles (Alt spreads them) - `ensure_main_thread` returns a `Future` (not `None`) unless `await_return` - `QIconifyIcon` needs pyconify (the `iconify` extra) - `QSearchableTreeWidget` filters on keys and values, not only keys - `QColormapLineEdit()` doesn't make the colormap fill the combo box (`setFractionalColormapWidth(1)` does) - unsupported `QQuantity` units raise `NotImplementedError` - `QFlowLayout` is a layout, not a QWidget; PyQt5 support is 5.15 Filled in what was missing: installing a Qt binding and the optional extras, pages for `QElidingLineEdit` and `qimage_to_array`, every public utility in the utilities index, examples for throttling, signal blocking and font icon animations, and descriptions of the options of each widget. Examples use realistic text and values (e.g. a `QLargeIntSpinBox` value beyond 32 bits). Also updated the setup instructions in CONTRIBUTING.md (uv, prek), and two docstrings that rendered wrong in the API reference. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 14 +-- README.md | 2 +- docs/_scenes.py | 17 +++- docs/examples/code_syntax_highlight.py | 14 +-- docs/examples/fonticon.py | 8 +- docs/examples/fonticon_animation.py | 20 ++++ docs/examples/qelidinglabel.py | 11 +-- docs/examples/qelidinglineedit.py | 13 +++ docs/examples/qlargeintspinbox.py | 8 +- docs/examples/qsearchablelistwidget.py | 6 +- docs/examples/qtoggleswitch.py | 3 +- docs/faq.md | 39 ++++---- docs/index.md | 52 ++++++---- docs/utilities/cmap.md | 9 +- docs/utilities/code_syntax_highlight.md | 14 ++- docs/utilities/error_dialog_contexts.md | 6 +- docs/utilities/fonticon.md | 97 +++++++++---------- docs/utilities/iconify.md | 31 +++--- docs/utilities/images.md | 8 ++ docs/utilities/index.md | 85 +++++++++------- docs/utilities/qmessagehandler.md | 9 +- docs/utilities/signal_utils.md | 14 ++- docs/utilities/thread_decorators.md | 86 ++++++++-------- docs/utilities/threading.md | 52 +++++++--- docs/utilities/throttling.md | 80 ++++++++------- docs/widgets/colormap_catalog.md | 24 +++-- docs/widgets/index.md | 46 +++++---- docs/widgets/qcollapsible.md | 11 ++- docs/widgets/qcolorcombobox.md | 12 ++- docs/widgets/qcolormap.md | 45 +++++---- docs/widgets/qdoublerangeslider.md | 3 +- docs/widgets/qdoubleslider.md | 4 +- docs/widgets/qelidinglabel.md | 12 ++- docs/widgets/qelidinglineedit.md | 19 ++++ docs/widgets/qenumcombobox.md | 35 ++++--- docs/widgets/qflowlayout.md | 4 +- docs/widgets/qlabeleddoublerangeslider.md | 4 +- docs/widgets/qlabeleddoubleslider.md | 5 +- docs/widgets/qlabeledrangeslider.md | 25 +++-- docs/widgets/qlabeledslider.md | 9 +- docs/widgets/qlargeintspinbox.md | 8 +- docs/widgets/qquantity.md | 27 +++--- docs/widgets/qrangeslider.md | 73 ++++++-------- docs/widgets/qsearchablecombobox.md | 8 +- docs/widgets/qsearchablelistwidget.md | 15 +-- docs/widgets/qsearchabletreewidget.md | 15 ++- docs/widgets/qtoggleswitch.md | 14 ++- src/superqt/cmap/_cmap_combo.py | 2 +- .../selection/_searchable_tree_widget.py | 2 +- zensical.toml | 8 +- 50 files changed, 678 insertions(+), 450 deletions(-) create mode 100644 docs/examples/fonticon_animation.py create mode 100644 docs/examples/qelidinglineedit.py create mode 100644 docs/utilities/images.md create mode 100644 docs/widgets/qelidinglineedit.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2f1fb6b7..26d00c1f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,14 +12,14 @@ To get started fork this repository, and clone your fork: git clone https://github.com//superqt cd superqt -# install in editable mode (this will install PyQt6 as the Qt backend) -pip install -e .[dev] +# create an environment with the dev dependencies, and PyQt6 as the Qt backend +uv sync --extra pyqt6 -# install pre-commit hooks -pre-commit install +# install the pre-commit hooks +uv run prek install # run tests & make sure everything is working! -pytest +uv run pytest ``` ## Targeted platforms @@ -27,7 +27,7 @@ pytest All widgets must be well-tested, and should work on: - Python 3.11 and above -- PyQt5 (5.11 and above) & PyQt6 +- PyQt5 (5.15) & PyQt6 - PySide6 - macOS, Windows, & Linux @@ -48,7 +48,7 @@ All widgets should try to match the native Qt API as much as possible: ## Testing -Tests can be run in the current environment with `pytest`. +Tests can be run in the current environment with `uv run pytest`. ## Documentation diff --git a/README.md b/README.md index e393a786..28e35b35 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Components are tested on: - macOS, Windows, & Linux - Python 3.11 and above -- PyQt5 (5.11 and above) & PyQt6 +- PyQt5 (5.15) & PyQt6 - PySide6 ## Documentation diff --git a/docs/_scenes.py b/docs/_scenes.py index 6fe3d660..d90b51ec 100644 --- a/docs/_scenes.py +++ b/docs/_scenes.py @@ -80,7 +80,7 @@ def _single_scene(r: Recorder, window: QWidget) -> None: # Buttons, containers and layouts -@scene("qtoggleswitch") +@scene("qtoggleswitch", width=170) def _(r: Recorder, window: QWidget) -> None: r.click(window, QPoint(22, window.height() // 2)) r.wait(0.8) @@ -98,6 +98,21 @@ def _(r: Recorder, window: QWidget) -> None: r.leave() +@scene("qelidinglineedit", width=300) +def _(r: Recorder, window: QWidget) -> None: + r.click(window, QPoint(150, window.height() // 2)) + r.key(window, Qt.Key.Key_End) + r.leave(duration=0.3) + r.wait(1.2) + window.clearFocus() + r.wait(0.3) + + +@scene("fonticon_animation") +def _(r: Recorder, window: QWidget) -> None: + r.wait(2.4) + + @scene("qelidinglabel", width=300) def _(r: Recorder, window: QWidget) -> None: r.resize(150, duration=1.2) diff --git a/docs/examples/code_syntax_highlight.py b/docs/examples/code_syntax_highlight.py index e75fead4..c9ccd26a 100644 --- a/docs/examples/code_syntax_highlight.py +++ b/docs/examples/code_syntax_highlight.py @@ -1,4 +1,3 @@ -from qtpy.QtGui import QColor, QPalette from qtpy.QtWidgets import QApplication, QTextEdit from superqt.utils import CodeSyntaxHighlight @@ -6,13 +5,9 @@ app = QApplication([]) text_area = QTextEdit() - -highlight = CodeSyntaxHighlight(text_area.document(), "python", "monokai") - -palette = text_area.palette() -palette.setColor(QPalette.Base, QColor(highlight.background_color)) -text_area.setPalette(palette) -text_area.setText( +# (given the QTextEdit, rather than its document, it also sets the background) +highlight = CodeSyntaxHighlight(text_area, "python", "monokai") +text_area.setPlainText( """from argparse import ArgumentParser def main(): @@ -26,8 +21,7 @@ def main(): main() """ ) - -text_area.show() text_area.resize(400, 200) +text_area.show() app.exec() diff --git a/docs/examples/fonticon.py b/docs/examples/fonticon.py index 9f5f6dfe..997296e6 100644 --- a/docs/examples/fonticon.py +++ b/docs/examples/fonticon.py @@ -6,9 +6,9 @@ app = QApplication([]) -btn2 = QPushButton() -btn2.setIcon(icon(FA5S.smile, color="blue")) -btn2.setIconSize(QSize(225, 225)) -btn2.show() +button = QPushButton() +button.setIcon(icon(FA5S.smile, color="royalblue")) +button.setIconSize(QSize(96, 96)) +button.show() app.exec() diff --git a/docs/examples/fonticon_animation.py b/docs/examples/fonticon_animation.py new file mode 100644 index 00000000..ddc097e5 --- /dev/null +++ b/docs/examples/fonticon_animation.py @@ -0,0 +1,20 @@ +from fonticon_fa5 import FA5S +from qtpy.QtWidgets import QApplication, QHBoxLayout, QPushButton, QWidget + +from superqt.fonticon import icon, pulse, spin + +app = QApplication([]) + +window = QWidget() +layout = QHBoxLayout(window) + +spinning = QPushButton("spin") +spinning.setIcon(icon(FA5S.sync, animation=spin(spinning))) +layout.addWidget(spinning) + +pulsing = QPushButton("pulse") +pulsing.setIcon(icon(FA5S.spinner, animation=pulse(pulsing))) +layout.addWidget(pulsing) + +window.show() +app.exec() diff --git a/docs/examples/qelidinglabel.py b/docs/examples/qelidinglabel.py index 763a4eee..16943873 100644 --- a/docs/examples/qelidinglabel.py +++ b/docs/examples/qelidinglabel.py @@ -4,12 +4,11 @@ app = QApplication([]) -widget = QElidingLabel( - "a skj skjfskfj sdlf sdfl sdlfk jsdf sdlkf jdsf dslfksdl sdlfk sdf sdl " - "fjsdlf kjsdlfk laskdfsal as lsdfjdsl kfjdslf asfd dslkjfldskf sdlkfj" +label = QElidingLabel( + "This text is too long for the label, so the end of it is replaced with an " + "ellipsis. Make the window wider to see more of it." ) -widget.setWordWrap(True) -widget.resize(300, 20) -widget.show() +label.resize(300, 20) +label.show() app.exec() diff --git a/docs/examples/qelidinglineedit.py b/docs/examples/qelidinglineedit.py new file mode 100644 index 00000000..18535aee --- /dev/null +++ b/docs/examples/qelidinglineedit.py @@ -0,0 +1,13 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QElidingLineEdit + +app = QApplication([]) + +line_edit = QElidingLineEdit( + "/Users/me/Documents/projects/experiments/2026-11-12/results/summary.csv" +) +line_edit.resize(300, 30) +line_edit.show() + +app.exec() diff --git a/docs/examples/qlargeintspinbox.py b/docs/examples/qlargeintspinbox.py index 71320ce9..273bd7a4 100644 --- a/docs/examples/qlargeintspinbox.py +++ b/docs/examples/qlargeintspinbox.py @@ -4,9 +4,9 @@ app = QApplication([]) -slider = QLargeIntSpinBox() -slider.setRange(0, 4.53e8) -slider.setValue(4.53e8) -slider.show() +spin = QLargeIntSpinBox() +spin.setRange(0, 10**15) +spin.setValue(2**40) # a QSpinBox can't go above 2**31 - 1 +spin.show() app.exec() diff --git a/docs/examples/qsearchablelistwidget.py b/docs/examples/qsearchablelistwidget.py index 336ab967..46515d07 100644 --- a/docs/examples/qsearchablelistwidget.py +++ b/docs/examples/qsearchablelistwidget.py @@ -4,8 +4,8 @@ app = QApplication([]) -slider = QSearchableListWidget() -slider.addItems(["foo", "bar", "baz", "foobar", "foobaz", "barbaz"]) -slider.show() +widget = QSearchableListWidget() +widget.addItems(["foo", "bar", "baz", "foobar", "foobaz", "barbaz"]) +widget.show() app.exec() diff --git a/docs/examples/qtoggleswitch.py b/docs/examples/qtoggleswitch.py index e77294d9..0e47b9ff 100644 --- a/docs/examples/qtoggleswitch.py +++ b/docs/examples/qtoggleswitch.py @@ -4,7 +4,8 @@ app = QApplication([]) -switch = QToggleSwitch() +switch = QToggleSwitch("Notifications") +switch.toggled.connect(print) switch.show() app.exec() diff --git a/docs/faq.md b/docs/faq.md index 0fd1edc0..67cbe52b 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1,23 +1,26 @@ # FAQ -## Sliders not dragging properly on MacOS 12+ - -??? details - On MacOS Monterey, with Qt5, there is a bug that causes all sliders - (including native Qt sliders) to not respond properly to drag events. See: - - - [https://bugreports.qt.io/browse/QTBUG-98093](https://bugreports.qt.io/browse/QTBUG-98093) - - [https://github.com/pyapp-kit/superqt/issues/74](https://github.com/pyapp-kit/superqt/issues/74) - - Superqt includes a workaround for this issue, but it is not perfect, and it requires using a custom stylesheet (which may interfere with your own styles). Note that you - may not see this issue if you're already using custom stylesheets. - - To opt in to the workaround, do any of the following: - - - set the environment variable `USE_MAC_SLIDER_PATCH=1` before importing superqt - (note: this is safe to use even if you're targeting more than just MacOS 12, it will only be applied when needed) - - call the `applyMacStylePatch()` method on any of the superqt slider subclasses (note, this will override your slider styles) - - apply the stylesheet manually: +## Sliders not dragging properly on macOS 12+ + +With Qt 5 on macOS 12 (Monterey) and later, a bug in Qt makes all sliders, +including Qt's own, respond badly to dragging +([QTBUG-98093](https://bugreports.qt.io/browse/QTBUG-98093), and +[superqt#74](https://github.com/pyapp-kit/superqt/issues/74)). Qt 6 doesn't have +this bug. + +superqt includes a workaround: a style sheet for the sliders. It isn't perfect, +and it replaces the sliders' styles (so it may interfere with your own; and if +you already style your sliders, you may not see the bug). To use it, do one of +the following: + +- Set the environment variable `USE_MAC_SLIDER_PATCH=1` before importing + superqt. superqt's sliders then use the style sheet if they run with Qt 5 on + macOS 12 or later (so it's safe to set on other platforms). This applies to all + of them except `QLabeledSlider`, which contains a plain `QSlider`. +- Call the `applyMacStylePatch()` method of a `QDoubleSlider`, `QRangeSlider`, + or `QDoubleRangeSlider`. This applies the style sheet whatever the platform, + and replaces the slider's style sheet. +- Apply the style sheet yourself, to any slider: ```python from superqt.sliders import MONTEREY_SLIDER_STYLES_FIX diff --git a/docs/index.md b/docs/index.md index 786592d3..3d054b4a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -11,10 +11,12 @@ hide:

"Missing" widgets and components for PyQt and PySide.

-This repository aims to provide high-quality community-contributed Qt widgets -and components for [PyQt](https://riverbankcomputing.com/software/pyqt/) & -[PySide](https://www.qt.io/qt-for-python) that are not provided in the native -QtWidgets module. +superqt is a collection of Qt widgets and utilities that the `QtWidgets` module +doesn't provide: range sliders, sliders for floats, searchable combo boxes and +lists, collapsible sections, font and SVG icons, tools for threading and for +throttling signals, and more. It is built on +[qtpy](https://github.com/spyder-ide/qtpy), so the same code works with PyQt5, +PyQt6, and PySide6. [Widgets](widgets/index.md){ .md-button .md-button--primary } [Utilities](utilities/index.md){ .md-button } @@ -45,27 +47,43 @@ QtWidgets module. conda install -c conda-forge superqt ``` -Components are tested on: +superqt doesn't install a Qt binding. If your environment doesn't have one yet, +install one with an extra: -- macOS, Windows, & Linux -- Python 3.11 and above -- PyQt5 (5.11 and above) & PyQt6 -- PySide6 +```bash +pip install "superqt[pyqt6]" # or [pyqt5], or [pyside6] +``` + +Some features need extra dependencies, which can also be installed as extras: + +| Extra | Installs | Needed for | +| --- | --- | --- | +| `cmap` | [cmap](https://cmap-docs.readthedocs.io/) | [`QColormapComboBox`](widgets/qcolormap.md), [`CmapCatalogComboBox`](widgets/colormap_catalog.md), [colormap utilities](utilities/cmap.md) | +| `quantity` | [pint](https://pint.readthedocs.io/) | [`QQuantity`](widgets/qquantity.md) | +| `iconify` | [pyconify](https://github.com/pyapp-kit/pyconify) | [`QIconifyIcon`](utilities/iconify.md) | +| `font-fa5`, `font-fa6` | Font Awesome 5 or 6 | [font icons](utilities/fonticon.md) | +| `font-mi6`, `font-mi7` | Material Design Icons 6 or 7 | [font icons](utilities/fonticon.md) | + +superqt is tested on macOS, Windows, and Linux, with Python 3.11 and later, and +with PyQt5 (5.15), PyQt6, and PySide6. ## Widgets [All widgets](widgets/index.md){ .md-button } ## Utilities -See the [Utilities](utilities/index.md) page for font icons, threading tools, -throttling and debouncing, and more. +The [utilities](utilities/index.md) include icons from icon fonts and from +Iconify, decorators and workers for running code in other threads, throttling and +debouncing of functions and signals, syntax highlighting, and context managers +for blocking signals, capturing Qt's log messages, and showing exceptions in a +dialog. diff --git a/docs/utilities/cmap.md b/docs/utilities/cmap.md index 06b571dd..7d8341c5 100644 --- a/docs/utilities/cmap.md +++ b/docs/utilities/cmap.md @@ -1,9 +1,10 @@ # Colormap utilities -See also: - -- [`superqt.QColormapComboBox`](../widgets/qcolormap.md) -- [`superqt.cmap.CmapCatalogComboBox`](../widgets/colormap_catalog.md) +The building blocks of the colormap widgets +([`QColormapComboBox`](../widgets/qcolormap.md) and +[`CmapCatalogComboBox`](../widgets/colormap_catalog.md)), for drawing +[cmap](https://cmap-docs.readthedocs.io/) colormaps elsewhere. They need the +`cmap` extra (`pip install "superqt[cmap]"`). ::: superqt.cmap.draw_colormap diff --git a/docs/utilities/code_syntax_highlight.md b/docs/utilities/code_syntax_highlight.md index 633b01a3..edaaf12f 100644 --- a/docs/utilities/code_syntax_highlight.md +++ b/docs/utilities/code_syntax_highlight.md @@ -1,13 +1,11 @@ # CodeSyntaxHighlight -A code highlighter subclass of `QSyntaxHighlighter` -that can be used to highlight code in a QTextEdit. - -Code lexer and available styles are from [`pygments`](https://pygments.org/) python library - -List of available languages are available [here](https://pygments.org/languages/). - -List of available styles are available [here](https://pygments.org/styles/). +A [`QSyntaxHighlighter`](https://doc.qt.io/qt-6/qsyntaxhighlighter.html) that +highlights code in a `QTextEdit` (or any `QTextDocument`), using +[Pygments](https://pygments.org/). It takes the name of a +[language](https://pygments.org/languages/) and of a +[style](https://pygments.org/styles/), which can be changed later with +`setLanguage` and `setTheme`. ## Example diff --git a/docs/utilities/error_dialog_contexts.md b/docs/utilities/error_dialog_contexts.md index ef9150f3..f82f5878 100644 --- a/docs/utilities/error_dialog_contexts.md +++ b/docs/utilities/error_dialog_contexts.md @@ -1,3 +1,7 @@ -# Error message context manager +# Showing exceptions in a dialog + +`exceptions_as_dialog` is a context manager that catches exceptions raised in +its block, and shows them in a `QMessageBox` (or a `QErrorMessage`, which lets +the user hide messages they've seen), instead of letting them propagate. ::: superqt.utils.exceptions_as_dialog diff --git a/docs/utilities/fonticon.md b/docs/utilities/fonticon.md index 027f4793..2f0b556a 100644 --- a/docs/utilities/fonticon.md +++ b/docs/utilities/fonticon.md @@ -1,10 +1,16 @@ # Font icons -The `superqt.fonticon` module provides a set of utilities for working with font -icons such as [Font Awesome](https://fontawesome.com/) or [Material Design -Icons](https://materialdesignicons.com/). +`superqt.fonticon` creates `QIcon`s from the glyphs of icon fonts, such as +[Font Awesome](https://fontawesome.com/) or +[Material Design Icons](https://pictogrammers.com/library/mdi/). Unlike images, +glyphs can be drawn at any size and in any color. -## Basic Example +Icon fonts are installed as plugins (see [below](#font-icon-plugins)), and glyphs +are referred to by a key in the form `"prefix.name"`, such as `"fa5s.smile"`. The +plugins also provide classes with a constant for each glyph, such as +`FA5S.smile`, which IDEs can autocomplete. + +## Basic example {{ show_widget() }} @@ -14,62 +20,54 @@ examples/fonticon.py --8<-- ``` -## Font Icon plugins - -Ready-made fonticon packs are available as plugins. - -A great way to search across most available icons libraries from a single -search interface is to use glyphsearch: - -If a font library you'd like to use is unavailable as a superqt plugin, -please [open a feature request](https://github.com/pyapp-kit/superqt/issues/new/choose) - -### Font Awesome 6 +`icon` takes options for the color, scale, and animation of the glyph, and +different options for each state and mode of the icon (as in +`QIcon.State` and `QIcon.Mode`); see [`icon`](#superqt.fonticon.icon) below. -Browse available icons at - -```bash -pip install fonticon-fontawesome6 -``` +## Animations -### Font Awesome 5 +The `animation` argument of `icon()` takes an +[`Animation`](#superqt.fonticon.Animation), such as `spin` or `pulse`, created +with the widget that shows the icon: -Browse available icons at +{{ show_widget("fonticon_animation") }} -```bash -pip install fonticon-fontawesome5 +```python +--8<-- +examples/fonticon_animation.py +--8<-- ``` -### Material Design Icons 7 +## Font icon plugins -Browse available icons at +These icon fonts are available as plugins, and as extras of superqt: -```bash -pip install fonticon-materialdesignicons7 -``` +| Font | Install | Browse the icons | +| --- | --- | --- | +| Font Awesome 6 | `pip install "superqt[font-fa6]"` | | +| Font Awesome 5 | `pip install "superqt[font-fa5]"` | | +| Material Design Icons 7 | `pip install "superqt[font-mi7]"` | | +| Material Design Icons 6 | `pip install "superqt[font-mi6]"` | (shows version 7: see the [changes from version 6](https://pictogrammers.com/docs/library/mdi/releases/changelog/)) | -### Material Design Icons 6 +Other fonts are available as separate packages: -Browse available icons at -(note that the search defaults to v7, see changes from v6 in [the -changelog](https://pictogrammers.com/docs/library/mdi/releases/changelog/)) - -```bash -pip install fonticon-materialdesignicons6 -``` +- [fonticon-bootstrapicons](https://github.com/tlambert03/fonticon-bootstrapicons) +- [fonticon-linearicons](https://github.com/tlambert03/fonticon-linearicons) +- [fonticon-feather](https://github.com/tlambert03/fonticon-feather) -### See also +[GlyphSearch](https://glyphsearch.com/) searches several icon libraries at once. +If you'd like to use a font that isn't available as a plugin, please +[open a feature request](https://github.com/pyapp-kit/superqt/issues/new/choose). -- -- -- +### Writing a plugin -`superqt.fonticon` is a pluggable system, and font icon packs may use the `"superqt.fonticon"` -entry point to register themselves with superqt. See [`fonticon-cookiecutter`](https://github.com/tlambert03/fonticon-cookiecutter) for a template, or look through the following repos for examples: - -- -- -- +Font packages register themselves with the `"superqt.fonticon"` +[entry point](https://packaging.python.org/en/latest/specifications/entry-points/). +[fonticon-cookiecutter](https://github.com/tlambert03/fonticon-cookiecutter) is +a template for a new one, and the packages above are examples, such as +[fonticon-fontawesome6](https://github.com/tlambert03/fonticon-fontawesome6). +To use a font file without writing a package, see +[`addFont`](#superqt.fonticon.addFont). ## API @@ -97,11 +95,6 @@ entry point to register themselves with superqt. See [`fonticon-cookiecutter`](h options: heading_level: 3 -## Animations - -the `animation` parameter to `icon()` accepts a subclass of -`Animation` that will be - ::: superqt.fonticon.Animation options: heading_level: 3 diff --git a/docs/utilities/iconify.md b/docs/utilities/iconify.md index 5cf7b627..3aad2f4e 100644 --- a/docs/utilities/iconify.md +++ b/docs/utilities/iconify.md @@ -1,17 +1,26 @@ # QIconifyIcon -[Iconify](https://iconify.design/) is an icon library that includes 150,000+ -icons from most major icon sets including Bootstrap, FontAwesome, Material -Design, and many more; each available as individual SVGs. Unlike the -[`superqt.fonticon` module](./fonticon.md), `superqt.QIconifyIcon` does not require any additional -dependencies or font files to be installed. Icons are downloaded (and cached) -on-demand from the Iconify API, using [pyconify](https://github.com/pyapp-kit/pyconify) +A `QIcon` with an SVG icon from [Iconify](https://iconify.design/), which +collects the icons of many open source icon sets (Bootstrap, Font Awesome, +Material Design, and many others). Icons are downloaded when they're first used +(with [pyconify](https://github.com/pyapp-kit/pyconify)), and cached on disk. +Unlike [font icons](fonticon.md), they don't need a package for each icon set. -Search available icons at -Once you find one you like, use the key in the format `"prefix:name"` to create an -icon: `QIconifyIcon("bi:bell")`. +!!! note "Requires pyconify" -## Basic Example + Install [pyconify](https://github.com/pyapp-kit/pyconify) with the `iconify` + extra: + + ```bash + pip install "superqt[iconify]" + ``` + +Search for icons at , and create one with its +key, in the form `"prefix:name"`: `QIconifyIcon("bi:bell")`. Icons can also be +colored, flipped, and rotated, and `addKey` adds icons for other modes and states +of the same `QIcon`. + +## Example {{ show_widget() }} @@ -23,4 +32,4 @@ examples/iconify.py ::: superqt.QIconifyIcon options: - heading_level: 3 + heading_level: 2 diff --git a/docs/utilities/images.md b/docs/utilities/images.md new file mode 100644 index 00000000..b2a8997c --- /dev/null +++ b/docs/utilities/images.md @@ -0,0 +1,8 @@ +# Image conversion + +!!! note "Requires NumPy" + + `qimage_to_array` returns a NumPy array, and NumPy isn't a dependency of + superqt: install it separately. + +::: superqt.utils.qimage_to_array diff --git a/docs/utilities/index.md b/docs/utilities/index.md index 743ae8ec..b2ab323a 100644 --- a/docs/utilities/index.md +++ b/docs/utilities/index.md @@ -1,38 +1,57 @@ # Utilities -## Font Icons - -| Object | Description | -| ----------- | --------------------- | -| [`addFont`](./fonticon.md#superqt.fonticon.addFont) | Add an `OTF/TTF` file at to the font registry. | -| [`font`](./fonticon.md#superqt.fonticon.font) | Create `QFont` for a given font-icon font family key | -| [`icon`](./fonticon.md#superqt.fonticon.icon) | Create a `QIcon` for font-con glyph key | -| [`setTextIcon`](./fonticon.md#superqt.fonticon.setTextIcon) | Set text on a `QWidget` to a specific font & glyph. | -| [`IconFont`](./fonticon.md#superqt.fonticon.IconFont) | Helper class that provides a standard way to create an `IconFont`. | -| [`IconOpts`](./fonticon.md#superqt.fonticon.IconOpts) | Options for rendering an icon | -| [`Animation`](./fonticon.md#superqt.fonticon.Animation) | Base class for adding animations to a font-icon. | - -## SVG Icons - -| Object | Description | -| ----------- | --------------------- | -| [`QIconifyIcon`](./iconify.md) | QIcons backed by the [Iconify](https://iconify.design/) icon library. | - -## Threading tools - -| Object | Description | -| ----------- | --------------------- | -| [`ensure_main_thread`](./thread_decorators.md#ensure_main_thread) | Decorator that ensures a function is called in the main `QApplication` thread. | -| [`ensure_object_thread`](./thread_decorators.md#ensure_object_thread) | Decorator that ensures a `QObject` method is called in the object's thread. | -| [`FunctionWorker`](./threading.md#superqt.utils.FunctionWorker) | `QRunnable` with signals that wraps a simple long-running function. | -| [`GeneratorWorker`](./threading.md#superqt.utils.GeneratorWorker) | `QRunnable` with signals that wraps a long-running generator. | -| [`create_worker`](./threading.md#superqt.utils.create_worker) | Create a worker to run a target function in another thread. | -| [`thread_worker`](./threading.md#superqt.utils.thread_worker) | Decorator for `create_worker`, turn a function into a worker. | +Functions, classes, and decorators for working with Qt, in `superqt.utils`, +`superqt.fonticon`, and `superqt.cmap`. + +## Icons + +| Object | Description | +| --- | --- | +| [`icon`](fonticon.md#superqt.fonticon.icon) | Create a `QIcon` from a glyph in an icon font. | +| [`setTextIcon`](fonticon.md#superqt.fonticon.setTextIcon) | Show a glyph from an icon font as the text of a widget. | +| [`font`](fonticon.md#superqt.fonticon.font) | Create the `QFont` of an icon font. | +| [`addFont`](fonticon.md#superqt.fonticon.addFont) | Add an OTF or TTF font file to the icon font registry. | +| [`IconFont`](fonticon.md#superqt.fonticon.IconFont) | Base class for defining the glyphs of an icon font. | +| [`IconOpts`](fonticon.md#superqt.fonticon.IconOpts) | Options for drawing an icon in a given state (color, scale, and so on). | +| [`Animation`](fonticon.md#superqt.fonticon.Animation), [`spin`](fonticon.md#superqt.fonticon.spin), [`pulse`](fonticon.md#superqt.fonticon.pulse) | Animations for font icons. | +| [`QIconifyIcon`](iconify.md) | A `QIcon` with any of the SVG icons from [Iconify](https://iconify.design/). | + +## Threading + +| Object | Description | +| --- | --- | +| [`thread_worker`](threading.md#superqt.utils.thread_worker) | Decorator that makes a function, or generator, run in another thread when called. | +| [`create_worker`](threading.md#superqt.utils.create_worker) | Create a worker that runs a function, or generator, in another thread. | +| [`FunctionWorker`](threading.md#superqt.utils.FunctionWorker) | `QRunnable` with signals, that runs a function. | +| [`GeneratorWorker`](threading.md#superqt.utils.GeneratorWorker) | `QRunnable` with signals, that runs a generator (and can be paused, resumed, and sent values). | +| [`WorkerBase`](threading.md#superqt.utils.WorkerBase) | Base class of the workers. | +| [`new_worker_qthread`](threading.md#superqt.utils.new_worker_qthread) | Run a `QObject` worker in a new `QThread`. | +| [`ensure_main_thread`](thread_decorators.md) | Decorator that makes a function run in the main thread. | +| [`ensure_object_thread`](thread_decorators.md) | Decorator that makes a `QObject` method run in the object's thread. | + +## Signals + +| Object | Description | +| --- | --- | +| [`qthrottled`](throttling.md#superqt.utils.qthrottled) | Decorator that limits how often a function runs. | +| [`qdebounced`](throttling.md#superqt.utils.qdebounced) | Decorator that delays a function until it stops being called. | +| [`QSignalThrottler`](throttling.md#superqt.utils.QSignalThrottler) | Emits its `triggered` signal at most once per timeout, however often `throttle()` is called. | +| [`QSignalDebouncer`](throttling.md#superqt.utils.QSignalDebouncer) | Emits its `triggered` signal once `throttle()` hasn't been called for a timeout. | +| [`signals_blocked`](signal_utils.md#superqt.utils.signals_blocked) | Context manager that blocks the signals of `QObject`s. | + +## Messages and errors + +| Object | Description | +| --- | --- | +| [`QMessageHandler`](qmessagehandler.md) | Context manager that captures Qt's log messages (from `qDebug`, `qWarning`, and so on). | +| [`exceptions_as_dialog`](error_dialog_contexts.md) | Context manager that shows exceptions in a dialog. | ## Miscellaneous -| Object | Description | -| ----------- | --------------------- | -| [`QMessageHandler`](./qmessagehandler.md) | A context manager to intercept messages from Qt. | -| [`CodeSyntaxHighlight`](./code_syntax_highlight.md) | A `QSyntaxHighlighter` for code syntax highlighting. | -| [`draw_colormap`](./cmap.md) | Function that draws a colormap into any QPaintDevice. | +| Object | Description | +| --- | --- | +| [`CodeSyntaxHighlight`](code_syntax_highlight.md) | A `QSyntaxHighlighter` that highlights code with Pygments. | +| [`draw_colormap`](cmap.md#superqt.cmap.draw_colormap) | Draw a colormap onto a `QPainter` or `QPaintDevice`. | +| [`QColormapLineEdit`](cmap.md#superqt.cmap.QColormapLineEdit) | A `QLineEdit` that shows the colormap named by its text. | +| [`QColormapItemDelegate`](cmap.md#superqt.cmap.QColormapItemDelegate) | An item delegate that draws colormaps in item views. | +| [`qimage_to_array`](images.md) | Convert a `QImage` to a NumPy array. | diff --git a/docs/utilities/qmessagehandler.md b/docs/utilities/qmessagehandler.md index eeb928e8..3908cfc2 100644 --- a/docs/utilities/qmessagehandler.md +++ b/docs/utilities/qmessagehandler.md @@ -1,8 +1,9 @@ # QMessageHandler +A context manager that captures the messages that Qt logs (with `qDebug`, +`qWarning`, `qCritical`, and so on), instead of printing them, for example to +check for them in tests, or to send them to Python's `logging`. + ::: superqt.utils.QMessageHandler options: - heading_level: 3 - show_signature_annotations: True - docstring_style: numpy - show_bases: False + heading_level: 2 diff --git a/docs/utilities/signal_utils.md b/docs/utilities/signal_utils.md index cf629700..366caf97 100644 --- a/docs/utilities/signal_utils.md +++ b/docs/utilities/signal_utils.md @@ -1,3 +1,15 @@ -# Signal Utilities +# Blocking signals + +`signals_blocked` blocks the signals of one or more `QObject`s while its block +runs, and restores each object's previous state afterwards (like +[`QSignalBlocker`](https://doc.qt.io/qt-6/qsignalblocker.html), as a context +manager): + +```python +from superqt.utils import signals_blocked + +with signals_blocked(slider): + slider.setValue(10) # doesn't emit valueChanged +``` ::: superqt.utils.signals_blocked diff --git a/docs/utilities/thread_decorators.md b/docs/utilities/thread_decorators.md index b9ae9c41..9e36fd84 100644 --- a/docs/utilities/thread_decorators.md +++ b/docs/utilities/thread_decorators.md @@ -1,99 +1,95 @@ # Threading decorators -`superqt` provides two decorators that help to ensure that given function is -running in the desired thread: +Qt objects must generally be used from the thread they live in, and widgets +from the main (GUI) thread. These two decorators make a function run in the +right thread, whichever thread calls it: -## `ensure_main_thread` +`ensure_main_thread` +: Runs the decorated function, or method, in the main thread. -`ensure_main_thread` ensures that the decorated function/method runs in the main thread +`ensure_object_thread` +: Runs the decorated method of a `QObject` in the thread that the object lives + in (see Qt's [threads and QObjects](https://doc.qt.io/qt-6/threads-qobject.html#accessing-qobject-subclasses-from-other-threads)). -## `ensure_object_thread` - -`ensure_object_thread` ensures that a decorated bound method of a `QObject` runs -in the thread in which the instance lives ([see qt documentation for -details](https://doc.qt.io/qt-6/threads-qobject.html#accessing-qobject-subclasses-from-other-threads)). +They're meant for calling Qt code from code that doesn't use Qt (such as a +callback from another library's thread). Between Qt objects, signals and slots +already do this. ## Usage -By default, functions are executed asynchronously (they return immediately with -an instance of -[`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future)). - -To block and wait for the result, see [Synchronous mode](#synchronous-mode) +When called from another thread, the decorated function is queued to run in +its target thread, and the call returns a +[`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future) +at once. (When called from the target thread, the function runs right away, and +the `Future` it returns is already done.) ```python from qtpy.QtCore import QObject + from superqt import ensure_main_thread, ensure_object_thread @ensure_main_thread -def sample_function(): - print("This function will run in main thread") +def update_label(text): + print("this runs in the main thread") -class SampleObject(QObject): +class Counter(QObject): def __init__(self): super().__init__() self._value = 1 @ensure_main_thread - def sample_method1(self): - print("This method will run in main thread") + def show(self): + print("this runs in the main thread") @ensure_object_thread - def sample_method3(self): - import time - - print("sleeping") - time.sleep(1) - print("This method will run in object thread") + def reset(self): + print("this runs in the thread that the Counter lives in") @property def value(self): - print("return value") return self._value @value.setter @ensure_object_thread def value(self, value): - print("this setter will run in object thread") + print("setters work too") self._value = value ``` -As can be seen in this example these decorators can also be used for setters. - -These decorators should not be used as replacement of Qt Signals but rather to -interact with Qt objects from non Qt code. +## Waiting for the result -## Synchronous mode +To wait for the function to finish, and get its return value, pass +`await_return=True`. It waits for at most `timeout` milliseconds (1000 by +default), and then raises a `TimeoutError`. -If you'd like for the program to block and wait for the result of your function -call, use the `await_return=True` parameter, and optionally specify a timeout. +!!! warning -!!! important - - Using synchronous mode may significantly impact performance. + The calling thread is blocked while it waits. ```python +from concurrent.futures import Future + from superqt import ensure_main_thread @ensure_main_thread -def sample_function1(): +def get_one(): return 1 @ensure_main_thread(await_return=True) -def sample_function2(): +def get_two(): return 2 -assert sample_function1() is None -assert sample_function2() == 2 +@ensure_main_thread(await_return=True, timeout=10000) +def get_three(): + return 3 -# optionally, specify a timeout -@ensure_main_thread(await_return=True, timeout=10000) -def sample_function(): - return 1 +assert isinstance(get_one(), Future) +assert get_two() == 2 +assert get_three() == 3 ``` diff --git a/docs/utilities/threading.md b/docs/utilities/threading.md index efa100d3..eea9f349 100644 --- a/docs/utilities/threading.md +++ b/docs/utilities/threading.md @@ -1,19 +1,43 @@ # Thread workers -The objects in this module provide utilities for running tasks in a separate -thread. In general (with the exception of `new_worker_qthread`), everything -here wraps Qt's [QRunnable API](https://doc.qt.io/qt-6/qrunnable.html). - -The highest level object is the -[`@thread_worker`][superqt.utils.thread_worker] decorator. It was originally -written for `napari`, and was later extracted into `superqt`. You may also be -interested in reading the [napari -documentation](https://napari.org/stable/guides/threading.html#threading-in-napari-with-thread-worker) on this feature, -which provides a more in-depth/introductory usage guide. - -For additional control, you can create your own -[`FunctionWorker`][superqt.utils.FunctionWorker] or -[`GeneratorWorker`][superqt.utils.GeneratorWorker] objects. +Workers run a long task in another thread, so that the GUI stays responsive, +and report back with signals (such as `started`, `returned`, `errored`, +`finished`, and, for generators, `yielded`), which can safely update the GUI +from the main thread. Except for +`new_worker_qthread`, they use Qt's +[`QRunnable`](https://doc.qt.io/qt-6/qrunnable.html) and global +[`QThreadPool`](https://doc.qt.io/qt-6/qthreadpool.html). + +The simplest way to use them is the +[`@thread_worker`][superqt.utils.thread_worker] decorator. Calling a decorated +function returns a worker, which runs the function when it's started (or at +once, if callbacks are given with `connect=`): + +```python +import time + +from superqt.utils import thread_worker + + +@thread_worker +def long_task(n): + time.sleep(n) + return n + + +worker = long_task(2) +worker.returned.connect(print) +worker.start() +``` + +If the function is a generator, the worker is a +[`GeneratorWorker`][superqt.utils.GeneratorWorker]: it emits `yielded` for each +value, and can be paused, resumed, and aborted between them. Otherwise, it's a +[`FunctionWorker`][superqt.utils.FunctionWorker]. + +These tools were written for napari, and moved to superqt. The +[napari guide to threading](https://napari.org/stable/guides/threading.html#threading-in-napari-with-thread-worker) +describes them in more depth. ::: superqt.utils.WorkerBase diff --git a/docs/utilities/throttling.md b/docs/utilities/throttling.md index 8b2283a1..b33a85b8 100644 --- a/docs/utilities/throttling.md +++ b/docs/utilities/throttling.md @@ -1,46 +1,56 @@ -# Throttling & Debouncing +# Throttling and debouncing -These utilities allow you to throttle or debounce a function. This is useful -when you have a function that is called multiple times in a short period of -time, and you want to make sure it is only "actually" called once (or at least -no more than a certain frequency). +When a function is called many times in quick succession (for example, by a +slider's `valueChanged` signal while it's dragged), throttling and debouncing +limit how often it actually runs: -For background on throttling and debouncing, see: +- **Throttling** runs it at most once per timeout. With the default (leading) + policy, the first call runs at once, and further calls during the timeout are + combined into one call at its end. +- **Debouncing** waits until the calls have stopped for the timeout, and then + runs it once. -- -- +For more background, see +[Debouncing and throttling explained](https://css-tricks.com/debouncing-throttling-explained-examples/). -::: superqt.utils.qdebounced - options: - show_source: false - docstring_style: numpy - show_root_toc_entry: True - show_root_heading: True +The `qthrottled` and `qdebounced` decorators wrap a function: + +```python +from superqt.utils import qdebounced, qthrottled + + +@qthrottled(timeout=100) # milliseconds +def update_preview(value): ... + + +@qdebounced(timeout=300) +def save_settings(value): ... + + +slider.valueChanged.connect(update_preview) +slider.valueChanged.connect(save_settings) +``` + +The decorated function is called with the arguments of the last call that it +combined. The `QSignalThrottler` and `QSignalDebouncer` objects do the same for +signals: connect a signal to their `throttle()` slot, and their `triggered` +signal is emitted at the throttled (or debounced) rate: + +```python +from superqt.utils import QSignalThrottler + +throttler = QSignalThrottler() +throttler.setTimeout(100) +slider.valueChanged.connect(throttler.throttle) +throttler.triggered.connect(update_view) +``` ::: superqt.utils.qthrottled - options: - show_source: false - docstring_style: numpy - show_root_toc_entry: True - show_root_heading: True -::: superqt.utils.QSignalDebouncer - options: - show_source: false - docstring_style: numpy - show_root_toc_entry: True - show_root_heading: True +::: superqt.utils.qdebounced ::: superqt.utils.QSignalThrottler - options: - show_source: false - docstring_style: numpy - show_root_toc_entry: True - show_root_heading: True + +::: superqt.utils.QSignalDebouncer ::: superqt.utils._throttler.GenericSignalThrottler - options: - show_source: false - docstring_style: numpy - show_root_toc_entry: True - show_root_heading: True diff --git a/docs/widgets/colormap_catalog.md b/docs/widgets/colormap_catalog.md index d97fbf8b..de05e939 100644 --- a/docs/widgets/colormap_catalog.md +++ b/docs/widgets/colormap_catalog.md @@ -1,20 +1,24 @@ # CmapCatalogComboBox -Searchable `QComboBox` variant that contains the -[entire cmap colormap catalog](https://cmap-docs.readthedocs.io/en/latest/catalog/) +A [`QComboBox`](https://doc.qt.io/qt-6/qcombobox.html) with every colormap in the +[cmap catalog](https://cmap-docs.readthedocs.io/en/latest/catalog/). Typing in it +shows the colormaps whose names contain the text, and `currentColormap()` +returns a [`cmap.Colormap`][]. -!!! note "requires cmap" +!!! note "Requires cmap" - This widget uses the [cmap](https://cmap-docs.readthedocs.io/) library - to provide colormaps. You can install it with: + Colormaps come from the [cmap](https://cmap-docs.readthedocs.io/) library, + which you can install with the `cmap` extra: - ```shell - # use the `cmap` extra to include colormap support - pip install superqt[cmap] + ```bash + pip install "superqt[cmap]" ``` -You can limit the colormaps shown by setting the `categories` or -`interpolation` keyword arguments. +The `categories` and `interpolation` keyword arguments limit the colormaps to +those in some categories (such as `"sequential"`), or with one interpolation +(such as `"linear"`). By default, colormaps are listed by their short names, and +by their full names (`namespace:name`) only where two namespaces use the same +short name; pass `prefer_short_names=False` to always use full names. {{ show_widget() }} diff --git a/docs/widgets/index.md b/docs/widgets/index.md index 69a7ee51..445df4dc 100644 --- a/docs/widgets/index.md +++ b/docs/widgets/index.md @@ -5,54 +5,58 @@ hide: # Widgets -The following are QWidget subclasses: +Most of these widgets subclass the Qt widget they're most similar to, and follow +Qt's API conventions (`camelCase` names, `value()`/`setValue()` pairs, and +signals named like `valueChanged`), so they can be used wherever that widget +is. Each page lists the Qt class and what superqt adds to it. ## Sliders ## Numeric inputs ## Combo boxes ## Lists and trees ## Text and buttons ## Containers and layouts diff --git a/docs/widgets/qcollapsible.md b/docs/widgets/qcollapsible.md index 6e21e1d6..26bd0941 100644 --- a/docs/widgets/qcollapsible.md +++ b/docs/widgets/qcollapsible.md @@ -1,6 +1,15 @@ # QCollapsible -Collapsible `QFrame` that can be expanded or collapsed by clicking on the header. +A [`QFrame`](https://doc.qt.io/qt-6/qframe.html) with a header button that +hides or shows its contents, with an animation. Add contents with `addWidget`. + +- `expand()` and `collapse()` open and close it from code (pass + `animate=False` to skip the animation), and `toggled` emits `True` or + `False` when it opens or closes. +- `setExpandedIcon` and `setCollapsedIcon` change the header's icons (a + `QIcon`, or a string such as `"▼"`), and `setDuration` and + `setEasingCurve` change the animation. +- `setLocked(True)` keeps it from opening or closing, until it's unlocked. {{ show_widget() }} diff --git a/docs/widgets/qcolorcombobox.md b/docs/widgets/qcolorcombobox.md index a4388151..151b4aa2 100644 --- a/docs/widgets/qcolorcombobox.md +++ b/docs/widgets/qcolorcombobox.md @@ -1,6 +1,16 @@ # QColorComboBox -`QComboBox` designed to select from a specific set of colors. +A [`QComboBox`](https://doc.qt.io/qt-6/qcombobox.html) for choosing a color +from a list. Colors can be given as anything that `QColor` accepts (names, +hex strings, `QColor`s, and so on); `currentColor()` returns a `QColor`, and +`currentColorChanged` emits one. + +- With `setUserColorsAllowed(True)` (or `allow_user_colors=True`), an + "Add Color..." item at the end of the list opens a `QColorDialog`, and adds + the chosen color. +- `setInvalidColorPolicy` sets what happens when an invalid color is added: + it's ignored (`InvalidColorPolicy.Ignore`, the default), or it causes a + warning (`Warn`) or an exception (`Raise`). {{ show_widget() }} diff --git a/docs/widgets/qcolormap.md b/docs/widgets/qcolormap.md index dec62996..e0131239 100644 --- a/docs/widgets/qcolormap.md +++ b/docs/widgets/qcolormap.md @@ -1,24 +1,30 @@ # QColormapComboBox -`QComboBox` variant to select from a specific set of colormaps. +A [`QComboBox`](https://doc.qt.io/qt-6/qcombobox.html) for choosing a colormap +from a list. Each item shows the colormap, and `currentColormap()` returns a +[`cmap.Colormap`][]. -!!! note "requires cmap" +!!! note "Requires cmap" - This widget uses the [cmap](https://cmap-docs.readthedocs.io/) library - to provide colormaps. You can install it with: + Colormaps come from the [cmap](https://cmap-docs.readthedocs.io/) library, + which you can install with the `cmap` extra: - ```shell - # use the `cmap` extra to include colormap support - pip install superqt[cmap] + ```bash + pip install "superqt[cmap]" ``` -### ColorMapLike objects +Colormaps can be added in any of the forms that cmap accepts: the name of a +colormap in its catalog, a sequence of colors (which are interpolated), a +`cmap.Colormap`, and [others](https://cmap-docs.readthedocs.io/en/latest/colormaps/#colormaplike-objects). -Colormaps may be specified in a variety of ways, such as by name (string), an iterable of a color/color-like objects, or as -a [`cmap.Colormap`][] instance. See [cmap documentation for details on -all ColormapLike types](https://cmap-docs.readthedocs.io/en/latest/colormaps/#colormaplike-objects) +- Typing in the combo box filters the colormaps (turn this off with + `setFilterable(False)`). +- With `setUserAdditionsAllowed(True)` (or `allow_user_colormaps=True`), an + "Add Colormap..." item at the end of the list opens a dialog for choosing any + colormap in the [cmap catalog](https://cmap-docs.readthedocs.io/en/latest/catalog/). +- Right-clicking an item in the list shows a menu for removing it. -### Example +## Example {{ show_widget() }} @@ -28,21 +34,18 @@ examples/qcolormap.py --8<-- ``` -### Style Customization +## Customizing the appearance -Note that both the LineEdit and the dropdown can be styled to have the colormap -on the left, or fill the entire width of the widget. +By default, the colormap fills about a third of the combo box, next to its name, +and all of the width of the items in the list. Both can be changed. -To make the CombBox label colormap fill the entire width of the widget: +To make the colormap fill the whole width of the combo box: ```python -from superqt.cmap import QColormapLineEdit - -cmap_combo.setLineEdit(QColormapLineEdit()) +cmap_combo.lineEdit().setFractionalColormapWidth(1) ``` -To make the CombBox dropdown colormaps fill -less than the entire width of the widget: +To make the colormaps in the list fill a third of their width: ```python from superqt.cmap import QColormapItemDelegate diff --git a/docs/widgets/qdoublerangeslider.md b/docs/widgets/qdoublerangeslider.md index 281b4ae5..92a6de95 100644 --- a/docs/widgets/qdoublerangeslider.md +++ b/docs/widgets/qdoublerangeslider.md @@ -1,6 +1,7 @@ # QDoubleRangeSlider -Float variant of [`QRangeSlider`](qrangeslider.md). (see that page for more details). +A [`QRangeSlider`](qrangeslider.md) for `float` values: its range, values, and +steps are floats. See the `QRangeSlider` page for how range sliders work. {{ show_widget() }} diff --git a/docs/widgets/qdoubleslider.md b/docs/widgets/qdoubleslider.md index dc1bde27..ec58cc46 100644 --- a/docs/widgets/qdoubleslider.md +++ b/docs/widgets/qdoubleslider.md @@ -1,6 +1,8 @@ # QDoubleSlider -`QSlider` variant that accepts floating point values. +A [`QSlider`](https://doc.qt.io/qt-6/qslider.html) for `float` values. Its +range, value, and steps are floats (the default single step is `0.01`, and +the default page step is `0.1`). {{ show_widget() }} diff --git a/docs/widgets/qelidinglabel.md b/docs/widgets/qelidinglabel.md index 392f87c4..93435490 100644 --- a/docs/widgets/qelidinglabel.md +++ b/docs/widgets/qelidinglabel.md @@ -1,7 +1,15 @@ # QElidingLabel -`QLabel` variant that will elide text (i.e. add an ellipsis) -if it is too long to fit in the available space. +A [`QLabel`](https://doc.qt.io/qt-6/qlabel.html) that elides its text: when the +text is too long to fit, its end is replaced with an ellipsis ("…"). `text()` +still returns the full text. + +- `setElideMode` sets which part of the text is elided (the end, by default; + or the start or the middle), with a `Qt.TextElideMode`. +- With `setWordWrap(True)`, the text wraps onto as many lines as fit, and only + the last line is elided. + +For a line edit that does the same, see [`QElidingLineEdit`](qelidinglineedit.md). {{ show_widget() }} diff --git a/docs/widgets/qelidinglineedit.md b/docs/widgets/qelidinglineedit.md new file mode 100644 index 00000000..56cc5f2e --- /dev/null +++ b/docs/widgets/qelidinglineedit.md @@ -0,0 +1,19 @@ +# QElidingLineEdit + +A [`QLineEdit`](https://doc.qt.io/qt-6/qlineedit.html) that elides its text while +it isn't being edited: when the text is too long to fit, its end is replaced with +an ellipsis ("…"). When the line edit has focus, it shows the full text, for +editing. `text()` always returns the full text. + +As with [`QElidingLabel`](qelidinglabel.md), `setElideMode` sets which part of the +text is elided. + +{{ show_widget() }} + +```python +--8<-- +examples/qelidinglineedit.py +--8<-- +``` + +{{ show_members('superqt.QElidingLineEdit') }} diff --git a/docs/widgets/qenumcombobox.md b/docs/widgets/qenumcombobox.md index 1d34a9f8..28754575 100644 --- a/docs/widgets/qenumcombobox.md +++ b/docs/widgets/qenumcombobox.md @@ -1,16 +1,16 @@ # QEnumComboBox -`QEnumComboBox` is a variant of -[`QComboBox`](https://doc.qt.io/qt-6/qcombobox.html) that populates the items in -the combobox based on a python `Enum` class. In addition to all the methods -provided by `QComboBox`, this subclass adds the methods -`enumClass`/`setEnumClass` to get/set the current `Enum` class represented by -the combobox, and `currentEnum`/`setCurrentEnum` to get/set the current `Enum` -member in the combobox. There is also a new signal `currentEnumChanged(enum)` -analogous to `currentIndexChanged` and `currentTextChanged`. - -Method like `insertItem` and `addItem` are blocked and try of its usage will end -with `RuntimeError` +A [`QComboBox`](https://doc.qt.io/qt-6/qcombobox.html) with the members of a +Python `Enum` as its items. In addition to the `QComboBox` API, it has: + +- `enumClass()` and `setEnumClass()`, to get and set the `Enum`; +- `currentEnum()` and `setCurrentEnum()`, to get and set the current member; +- a `currentEnumChanged` signal, which emits the new member. + +Items are shown as `str(member)` if the `Enum` defines `__str__`, and otherwise +as the member's name, with underscores replaced by spaces. The items can only +come from the `Enum`: `addItem`, `addItems`, `insertItem`, and `insertItems` +raise a `RuntimeError`. {{ show_widget() }} @@ -20,7 +20,7 @@ examples/qenumcombobox.py --8<-- ``` -Another option is to use optional `enum_class` argument of constructor and change +The `Enum` can also be passed to the constructor: ```python # option A: @@ -32,7 +32,8 @@ combo = QEnumComboBox(enum_class=SampleEnum) ## Allow `None` -`QEnumComboBox` also allows using `Optional` type annotation: +With `allow_none=True`, the combo box has an extra item, `----`, for no +member: ```python from enum import Enum @@ -46,14 +47,12 @@ class SampleEnum(Enum): third = 3 -# as usual: -# you must create a QApplication before create a widget. - +# (a QApplication must exist before creating a widget) combo = QEnumComboBox() combo.setEnumClass(SampleEnum, allow_none=True) ``` -In this case there is added option `----` and the `currentEnum()` method will -return `None` when it is selected. +When it's selected, `currentEnum()` returns `None` (and `setCurrentEnum(None)` +selects it). {{ show_members('superqt.QEnumComboBox') }} diff --git a/docs/widgets/qflowlayout.md b/docs/widgets/qflowlayout.md index c126135c..2d52d076 100644 --- a/docs/widgets/qflowlayout.md +++ b/docs/widgets/qflowlayout.md @@ -1,6 +1,8 @@ # QFlowLayout -QLayout that rearranges items based on parent width. +A [`QLayout`](https://doc.qt.io/qt-6/qlayout.html) that places its items in a +row, left to right, and wraps them onto a new row when there's no more room, +like words in a paragraph. Resizing the widget rearranges them. {{ show_widget() }} diff --git a/docs/widgets/qlabeleddoublerangeslider.md b/docs/widgets/qlabeleddoublerangeslider.md index 6dc3a15d..c9b0ed5a 100644 --- a/docs/widgets/qlabeleddoublerangeslider.md +++ b/docs/widgets/qlabeleddoublerangeslider.md @@ -1,6 +1,8 @@ # QLabeledDoubleRangeSlider -Labeled Float variant of [`QRangeSlider`](qrangeslider.md). (see that page for more details). +A [`QDoubleRangeSlider`](qdoublerangeslider.md) with labels for its handles and +range. It works like a [`QLabeledRangeSlider`](qlabeledrangeslider.md); +`setDecimals` sets the number of decimals shown. {{ show_widget() }} diff --git a/docs/widgets/qlabeleddoubleslider.md b/docs/widgets/qlabeleddoubleslider.md index 54a7ae04..a68a2ad9 100644 --- a/docs/widgets/qlabeleddoubleslider.md +++ b/docs/widgets/qlabeleddoubleslider.md @@ -1,6 +1,9 @@ # QLabeledDoubleSlider -[`QDoubleSlider`](./qdoubleslider.md) variant that shows an editable (SpinBox) label next to the slider. +A [`QDoubleSlider`](qdoubleslider.md) with a label next to it that shows the +slider's value, which can be typed into the label. It works like a +[`QLabeledSlider`](qlabeledslider.md); `setDecimals` sets the number of +decimals shown. {{ show_widget() }} diff --git a/docs/widgets/qlabeledrangeslider.md b/docs/widgets/qlabeledrangeslider.md index 006b1003..cfa4d898 100644 --- a/docs/widgets/qlabeledrangeslider.md +++ b/docs/widgets/qlabeledrangeslider.md @@ -1,6 +1,19 @@ # QLabeledRangeSlider -Labeled variant of [`QRangeSlider`](qrangeslider.md). (see that page for more details). +A [`QRangeSlider`](qrangeslider.md) with labels: one above each handle, with +its value, and one at each end, with the minimum and maximum. A value typed +into a handle's label moves that handle, and a value typed into an end label +changes the minimum or maximum. + +- `setHandleLabelPosition` moves the handle labels: above + (`LabelPosition.LabelsAbove`, the default), below, on the handles + (`LabelPosition.LabelsOnHandle`), or nowhere (`LabelPosition.NoLabel`). +- `setEdgeLabelMode` sets what the end labels show: the range + (`EdgeLabelMode.LabelIsRange`, the default), the values of the first and + last handles (`EdgeLabelMode.LabelIsValue`; then typing into them moves those + handles), or nothing (`EdgeLabelMode.NoLabel`). +- With `setExpandRangeOnHandleEdit(True)`, typing a value outside of the range + into a handle's label expands the range to include it. {{ show_widget() }} @@ -10,11 +23,9 @@ examples/qlabeledrangeslider.py --8<-- ``` -{{ show_members('superqt.QLabeledRangeSlider') }} - ----- +!!! tip "Fine-tuning the label positions" -If you find that you need to fine tune the position of the handle labels: + The `label_shift_x` and `label_shift_y` attributes offset the handle labels + by that many pixels. -- `QLabeledRangeSlider.label_shift_x`: adjust horizontal label position -- `QLabeledRangeSlider.label_shift_y`: adjust vertical label position +{{ show_members('superqt.QLabeledRangeSlider') }} diff --git a/docs/widgets/qlabeledslider.md b/docs/widgets/qlabeledslider.md index b3527f12..fef37e20 100644 --- a/docs/widgets/qlabeledslider.md +++ b/docs/widgets/qlabeledslider.md @@ -1,6 +1,13 @@ # QLabeledSlider -`QSlider` variant that shows an editable (SpinBox) label next to the slider. +A slider with a label next to it that shows the slider's value. The value can +be typed into the label. + +`QLabeledSlider` is a [`QAbstractSlider`](https://doc.qt.io/qt-6/qabstractslider.html) +that wraps a `QSlider` and a label; slider methods such as `setRange` and +`setValue` work as they do on a `QSlider`. To move the label to the other side, +or hide it, use `setEdgeLabelPosition` (with `LabelPosition.LabelsLeft` or +`LabelPosition.NoLabel`). {{ show_widget() }} diff --git a/docs/widgets/qlargeintspinbox.md b/docs/widgets/qlargeintspinbox.md index 0c4e0ed8..54b98302 100644 --- a/docs/widgets/qlargeintspinbox.md +++ b/docs/widgets/qlargeintspinbox.md @@ -1,6 +1,12 @@ # QLargeIntSpinBox -`QSpinBox` variant that allows to enter large integers, without overflow. +A spin box for integers of any size. `QSpinBox` stores its value in a 32-bit +integer, so it can't go beyond ±2,147,483,647; `QLargeIntSpinBox` stores a +Python `int`, and its default maximum is `2**64 - 1`. + +It doesn't support the prefix, suffix, or special value text of `QSpinBox`. +Its `valueChanged` signal emits an `object` (a Python `int`), because a Qt +`int` couldn't carry large values. {{ show_widget() }} diff --git a/docs/widgets/qquantity.md b/docs/widgets/qquantity.md index 124dff0d..d53b150a 100644 --- a/docs/widgets/qquantity.md +++ b/docs/widgets/qquantity.md @@ -1,19 +1,16 @@ # QQuantity -A widget that allows the user to edit a quantity (a magnitude associated with a unit). +A widget for editing a quantity: a magnitude, in a spin box, and a unit, in a +combo box with the units of the same dimension (for meters: millimeters, +kilometers, and so on). The value is a +[`pint.Quantity`](https://pint.readthedocs.io/). -!!! note +!!! note "Requires pint" - This widget requires [`pint`](https://pint.readthedocs.io): + Install [pint](https://pint.readthedocs.io) with the `quantity` extra: - ``` - pip install pint - ``` - - or - - ``` - pip install superqt[quantity] + ```bash + pip install "superqt[quantity]" ``` {{ show_widget() }} @@ -24,10 +21,10 @@ examples/qquantity.py --8<-- ``` -!!! note +!!! warning "Only one dimension" - `QQuantity` currently supports simple units with exponents, e.g., `meters^2` or - `1/second`. However, compound units, e.g. `meter/second`, `Newton`, etc., - are not currently supported. + `QQuantity` supports units of a single dimension, with an exponent, such as + `meter ** 2` or `1 / second`. Units that combine dimensions, such as + `meter / second` or `newton`, raise a `NotImplementedError`. {{ show_members('superqt.QQuantity') }} diff --git a/docs/widgets/qrangeslider.md b/docs/widgets/qrangeslider.md index 6d4a5ced..ee6ffd81 100644 --- a/docs/widgets/qrangeslider.md +++ b/docs/widgets/qrangeslider.md @@ -1,7 +1,6 @@ # QRangeSlider -A multi-handle slider widget than can be used to -select a range of values. +A slider with two or more handles, to select a range of values. {{ show_widget() }} @@ -11,31 +10,34 @@ examples/qrangeslider.py --8<-- ``` -- `QRangeSlider` inherits from [`QSlider`](https://doc.qt.io/qt-6/qslider.html) - and attempts to match the Qt API as closely as possible -- It uses platform-specific styles (for handle, groove, & ticks) but also supports - QSS style sheets. -- Supports mouse wheel events -- Supports more than 2 handles (e.g. `slider.setValue([0, 10, 60, 80])`) +`QRangeSlider` is a [`QSlider`](https://doc.qt.io/qt-6/qslider.html), and +has the same API, except that `value()` and `sliderPosition()` are tuples with +one `int` for each handle (see [type changes](#type-changes)): -As `QRangeSlider` inherits from -[`QtWidgets.QSlider`](https://doc.qt.io/qt-6/qslider.html), you can use all of -the same methods available in the [QSlider -API](https://doc.qt.io/qt-6/qslider.html). The major difference is that `value()` -and `sliderPosition()` are reimplemented as `tuples` of `int` (where the length of -the tuple is equal to the number of handles in the slider.) +- The number of handles is the length of the value: + `slider.setValue([0, 10, 60, 80])` makes four. +- Handles can be dragged, and so can the bar between the outer handles, which + moves all of them. The mouse wheel also moves all of them (with ++alt++ held, + it spreads them apart or brings them together). +- The handles, groove, and ticks are drawn with the platform's style, and can be + styled with Qt style sheets (QSS). The color of the bar is the `barColor` + property (`qproperty-barColor` in QSS). -These options are in addition to the Qt QSlider API, and control the behavior of the bar between handles. +These methods, in addition to those of `QSlider`, control the bar between the +handles: -| getter | setter | type | default | description | -| -------------------- | ------------------------------------------- | ------ | ------- | ------------------------------------------------------------------------------------------------ | -| `barIsVisible` | `setBarIsVisible`
`hideBar` / `showBar` | `bool` | `True` | Whether the bar between handles is visible. | -| `barMovesAllHandles` | `setBarMovesAllHandles` | `bool` | `True` | Whether clicking on the bar moves all handles or just the nearest | -| `barIsRigid` | `setBarIsRigid` | `bool` | `True` | Whether bar length is constant or "elastic" when dragging the bar beyond min/max. | +| Getter | Setter | Default | Description | +| -------------------- | ------------------------------------------ | ------- | ----------------------------------------------------------------------------------- | +| `barIsVisible` | `setBarVisible`
`hideBar` / `showBar` | `True` | Whether the bar between the handles is shown. | +| `barMovesAllHandles` | `setBarMovesAllHandles` | `True` | Whether clicking on the bar moves all handles, or only the nearest one. | +| `barIsRigid` | `setBarIsRigid` | `True` | Whether the bar keeps its length when it's dragged against the minimum or maximum. | -### Screenshots +### Native styles -??? title "code that generates the images below" +`QRangeSlider` and `QSlider`, unstyled and with the same style sheet, on each +platform: + +??? example "Code for these screenshots" ```python import os @@ -188,29 +190,16 @@ These options are in addition to the Qt QSlider API, and control the behavior of ## Type changes -Note the following changes in types compared to the `QSlider` API: - -```python -value() -> Tuple[int, ...] -``` +Compared with `QSlider`, these methods and signals take or return one value +for each handle: ```python +value() -> tuple[int, ...] setValue(val: Sequence[int]) -> None -``` - -```python -# Signal -valueChanged(Tuple[int, ...]) -``` - -```python -sliderPosition() -> Tuple[int, ...] -``` - -```python +sliderPosition() -> tuple[int, ...] setSliderPosition(val: Sequence[int]) -> None -``` -```python -sliderMoved(Tuple[int, ...]) +# signals +valueChanged(tuple[int, ...]) # (also available as `valuesChanged`) +sliderMoved(tuple[int, ...]) # (also available as `slidersMoved`) ``` diff --git a/docs/widgets/qsearchablecombobox.md b/docs/widgets/qsearchablecombobox.md index e87c8f55..352e7dd0 100644 --- a/docs/widgets/qsearchablecombobox.md +++ b/docs/widgets/qsearchablecombobox.md @@ -1,9 +1,9 @@ # QSearchableComboBox -`QSearchableComboBox` is a variant of -[`QComboBox`](https://doc.qt.io/qt-6/qcombobox.html) that allow to filter list -of options by enter part of text. It could be drop in replacement for -`QComboBox`. +A [`QComboBox`](https://doc.qt.io/qt-6/qcombobox.html) that you can type into: +it shows a list of the items that contain the typed text (ignoring case), to +choose from. Items are added as in a `QComboBox`, and typed text that doesn't +match an item isn't added to it. {{ show_widget() }} diff --git a/docs/widgets/qsearchablelistwidget.md b/docs/widgets/qsearchablelistwidget.md index 36231370..f2edef2b 100644 --- a/docs/widgets/qsearchablelistwidget.md +++ b/docs/widgets/qsearchablelistwidget.md @@ -1,13 +1,14 @@ # QSearchableListWidget -`QSearchableListWidget` is a variant of -[`QListWidget`](https://doc.qt.io/qt-6/qlistwidget.html) that add text entry -above list widget that allow to filter list of available options. +A [`QListWidget`](https://doc.qt.io/qt-6/qlistwidget.html) with a text field +above it. Typing in the field hides the items that don't contain the text +(ignoring case). -Due to implementation details, this widget it does not inherit directly from -[`QListWidget`](https://doc.qt.io/qt-6/qlistwidget.html) but it does fully -satisfy its api. The only limitation is that it cannot be used as argument of -[`QListWidgetItem`](https://doc.qt.io/qt-6/qlistwidgetitem.html) constructor. +`QSearchableListWidget` is a `QWidget` that contains a `QListWidget` +(`list_widget`) and a `QLineEdit` (`filter_widget`), and forwards the methods of +`QListWidget` to the list, so it can be used like one. The difference is that it +isn't a `QListWidget`: it can't be passed as the parent of a `QListWidgetItem` +(use `list_widget` instead), and `isinstance` checks for `QListWidget` fail. {{ show_widget() }} diff --git a/docs/widgets/qsearchabletreewidget.md b/docs/widgets/qsearchabletreewidget.md index 71cec21b..b38fdd32 100644 --- a/docs/widgets/qsearchabletreewidget.md +++ b/docs/widgets/qsearchabletreewidget.md @@ -1,11 +1,16 @@ # QSearchableTreeWidget -`QSearchableTreeWidget` combines a -[`QTreeWidget`](https://doc.qt.io/qt-6/qtreewidget.html) and a `QLineEdit` for showing a mapping that can be searched by key. +A [`QTreeWidget`](https://doc.qt.io/qt-6/qtreewidget.html) that shows a mapping +(such as a `dict`), with a `QLineEdit` above it to filter it. Nested mappings and +sequences become branches of the tree, with keys (or indices) in the first +column and values in the second. -This is intended to be used with a read-only mapping and be conveniently created -using `QSearchableTreeWidget.fromData(data)`. If the mapping changes, the -easiest way to update this is by calling `setData`. +The filter is a [regular expression](https://doc.qt.io/qt-6/qregularexpression.html#details): +an item is shown if its key or value matches it, or if one of its ancestors' or +descendants' does. + +Create it with `QSearchableTreeWidget.fromData(data)`. It doesn't watch the +mapping for changes: call `setData` to show new data. {{ show_widget() }} diff --git a/docs/widgets/qtoggleswitch.md b/docs/widgets/qtoggleswitch.md index 264bf0a2..f1407567 100644 --- a/docs/widgets/qtoggleswitch.md +++ b/docs/widgets/qtoggleswitch.md @@ -1,10 +1,14 @@ # QToggleSwitch -`QToggleSwitch` is a -[`QAbstractButton`](https://doc.qt.io/qt-6/qabstractbutton.html) subclass -that represents a boolean value as a toggle switch. The API is similar to -[`QCheckBox`](https://doc.qt.io/qt-6/qcheckbox.html) but with a different -visual representation. +A checkable [`QAbstractButton`](https://doc.qt.io/qt-6/qabstractbutton.html) +drawn as a toggle switch, with an optional text label. It's used like a +[`QCheckBox`](https://doc.qt.io/qt-6/qcheckbox.html): `isChecked()`, +`setChecked()`, and the `toggled` signal. + +Its colors and size are properties (`onColor`, `offColor`, `handleColor`, +`switchWidth`, `switchHeight`, and `handleSize`), so they can also be set in a +style sheet, as in `QToggleSwitch { qproperty-onColor: red; }`. For other +looks, subclass it and reimplement `drawGroove`, `drawHandle`, or `drawText`. {{ show_widget() }} diff --git a/src/superqt/cmap/_cmap_combo.py b/src/superqt/cmap/_cmap_combo.py index dd2b4d0d..69932626 100644 --- a/src/superqt/cmap/_cmap_combo.py +++ b/src/superqt/cmap/_cmap_combo.py @@ -42,7 +42,7 @@ class QColormapComboBox(QComboBox): - """A drop down menu for selecting colors. + """A drop down menu for selecting colormaps. Parameters ---------- diff --git a/src/superqt/selection/_searchable_tree_widget.py b/src/superqt/selection/_searchable_tree_widget.py index 605f5f4a..d35733ba 100644 --- a/src/superqt/selection/_searchable_tree_widget.py +++ b/src/superqt/selection/_searchable_tree_widget.py @@ -24,7 +24,7 @@ class QSearchableTreeWidget(QWidget): tree : QTreeWidget Shows the mapping as a tree of items. filter : QLineEdit - Used to filter items in the tree by matching their key against a + Used to filter items in the tree by matching their key or value against a regular expression. """ diff --git a/zensical.toml b/zensical.toml index 38a3b43c..0ae6791d 100644 --- a/zensical.toml +++ b/zensical.toml @@ -56,6 +56,7 @@ nav = [ ] }, { "Text and buttons" = [ "widgets/qelidinglabel.md", + "widgets/qelidinglineedit.md", "widgets/qtoggleswitch.md", ] }, { "Containers and layouts" = [ @@ -73,15 +74,18 @@ nav = [ "utilities/threading.md", "utilities/thread_decorators.md", ] }, - { "Signals and events" = [ + { "Signals" = [ "utilities/throttling.md", "utilities/signal_utils.md", + ] }, + { "Messages and errors" = [ "utilities/qmessagehandler.md", "utilities/error_dialog_contexts.md", ] }, - { "Drawing" = [ + { "Miscellaneous" = [ "utilities/code_syntax_highlight.md", "utilities/cmap.md", + "utilities/images.md", ] }, ] }, { "FAQ" = "faq.md" }, From 913b20b8319300d88ac6b55e2a13c737265051bf Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Fri, 13 Nov 2026 15:41:55 +0100 Subject: [PATCH 04/10] fix: remove QIconifyIcon from superqt.fonticon.__all__ It isn't defined there, so `from superqt.fonticon import *` raised an AttributeError. Co-Authored-By: Claude Opus 5.5 --- src/superqt/fonticon/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/superqt/fonticon/__init__.py b/src/superqt/fonticon/__init__.py index d80bf37c..71e9dd84 100644 --- a/src/superqt/fonticon/__init__.py +++ b/src/superqt/fonticon/__init__.py @@ -6,7 +6,6 @@ "IconFont", "IconFontMeta", "IconOpts", - "QIconifyIcon", "addFont", "font", "icon", From 30bc716b433bd39242da894f2ef2660ef4e74dbe Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Fri, 13 Nov 2026 15:41:56 +0100 Subject: [PATCH 05/10] docs: card galleries, hover animations, icon section, and more examples - home page: new SVG logo, a gallery of 12 widgets and 3 utilities; cards show a still, and play their animation while hovered - widgets: a QColormapLineEdit page, sliders reordered, no edit button - utilities: an Icons section (overview and comparison, QIconifyIcon, font icons), with examples of colors, palettes, and states; a live throttling/debouncing demo; API sections for the remaining public names - media: native macOS rendering (`--style macos`), recorded clicks into popups and modal dialogs, seamless loops, and a shorter lead-in - QIconifyIcon's docstring: the current number of icons and icon sets Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 5 + docs/_gen_media.py | 1 + docs/_macros.py | 51 +++-- docs/_media.py | 246 ++++++++++++++++++++----- docs/_scenes.py | 195 ++++++++++++++++---- docs/examples/fonticon_animation.py | 6 +- docs/examples/iconify_color.py | 15 ++ docs/examples/iconify_palette.py | 15 ++ docs/examples/iconify_states.py | 17 ++ docs/examples/qcolormap.py | 3 +- docs/examples/qcolormaplineedit.py | 11 ++ docs/examples/qsearchabletreewidget.py | 1 + docs/examples/showcase.py | 1 + docs/examples/throttling.py | 93 ++++++++++ docs/faq.md | 6 + docs/images/logo-dark.svg | 20 ++ docs/images/logo.svg | 20 ++ docs/index.md | 33 +++- docs/javascripts/cards.js | 13 ++ docs/stylesheets/extra.css | 52 +++++- docs/utilities/cmap.md | 7 +- docs/utilities/fonticon.md | 108 ----------- docs/utilities/iconify.md | 35 ---- docs/utilities/icons/fonticon.md | 169 +++++++++++++++++ docs/utilities/icons/iconify.md | 112 +++++++++++ docs/utilities/icons/index.md | 41 +++++ docs/utilities/index.md | 28 +-- docs/utilities/thread_decorators.md | 10 + docs/utilities/throttling.md | 14 ++ docs/widgets/index.md | 5 +- docs/widgets/qcolormap.md | 2 + docs/widgets/qcolormaplineedit.md | 33 ++++ docs/widgets/qtoggleswitch.md | 9 +- src/superqt/iconify/__init__.py | 4 +- zensical.toml | 21 ++- 35 files changed, 1128 insertions(+), 274 deletions(-) create mode 100644 docs/examples/iconify_color.py create mode 100644 docs/examples/iconify_palette.py create mode 100644 docs/examples/iconify_states.py create mode 100644 docs/examples/qcolormaplineedit.py create mode 100644 docs/examples/throttling.py create mode 100644 docs/images/logo-dark.svg create mode 100644 docs/images/logo.svg create mode 100644 docs/javascripts/cards.js delete mode 100644 docs/utilities/fonticon.md delete mode 100644 docs/utilities/iconify.md create mode 100644 docs/utilities/icons/fonticon.md create mode 100644 docs/utilities/icons/iconify.md create mode 100644 docs/utilities/icons/index.md create mode 100644 docs/widgets/qcolormaplineedit.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 26d00c1f..c9310647 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,6 +62,11 @@ uv run --group docs python docs/_gen_media.py # renders into docs/_generated/ uv run --group docs zensical serve # preview at http://localhost:8000 ``` +By default, widgets are drawn offscreen with Qt's Fusion style. On macOS, +`--style macos` draws them with the native macOS style instead; this opens the +windows on screen while they're rendered, one at a time (so it takes a few +minutes), and they shouldn't be clicked or typed into until it's done. + To document a new widget: 1. Add a runnable example, `docs/examples/.py`, that shows one window. diff --git a/docs/_gen_media.py b/docs/_gen_media.py index f98fa7ce..10980b78 100644 --- a/docs/_gen_media.py +++ b/docs/_gen_media.py @@ -7,6 +7,7 @@ uv run --group docs python docs/_gen_media.py # everything uv run --group docs python docs/_gen_media.py qcollapsible --force + uv run --group docs python docs/_gen_media.py --style macos # native, on macOS """ import sys diff --git a/docs/_macros.py b/docs/_macros.py index fe7ff266..54cd58ad 100644 --- a/docs/_macros.py +++ b/docs/_macros.py @@ -5,8 +5,8 @@ import ast import inspect import json +import sys from enum import EnumMeta -from functools import cache from importlib import import_module from pathlib import Path from textwrap import dedent, indent @@ -32,11 +32,11 @@ def show_widget(name: str | None = None) -> str: page = env.variables["page"] name = name or Path(page.path).stem info = _manifest().get(name) - if info is None: - raise ValueError( - f"No screenshot for {name!r}: add docs/examples/{name}.py, and run " - "`uv run --group docs python docs/_gen_media.py`" - ) + if info is None: # (a warning, so that `zensical serve` keeps running) + msg = f"No screenshot of `{name}` yet: run `docs/_gen_media.py`." + print(f"warning: {msg}", file=sys.stderr) + return f'!!! warning "Missing screenshot"\n\n {msg}\n' + root = "../" * Path(page.path).as_posix().count("/") + "_generated/" animated = "animation" in info ext, size = ("webp", info["animation"]) if animated else ("png", info) @@ -52,30 +52,41 @@ def card(page_ref: str, title: str, description: str) -> str: """Gallery card linking to `page_ref`, with its widget's screenshot.""" page = env.variables["page"] name = Path(page_ref).stem - thumb = "" + thumb = style = "" if info := _manifest().get(name): root = "../" * Path(page.path).as_posix().count("/") + "_generated/" - attrs = f'width="{info["width"]}" loading=lazy' + # the still, and the animation (if any), which plays on hover + images = [("png", info, ".sq-card__still" if "animation" in info else "")] + if anim := info.get("animation"): + images.append(("webp", anim, ".sq-card__anim")) thumb = "".join( - f"![]({root}{name}-{theme}.png#only-{theme}){{ {attrs} }}" + f"![]({root}{name}-{theme}.{ext}#only-{theme})" + f'{{ {cls} width="{size["width"]}" loading=lazy }}' + for ext, size, cls in images for theme in ("light", "dark") ) + # match the window color of the screenshots + bg = info.get("background", {}) + style = "".join(f"--sq-thumb-{t}: {c}; " for t, c in bg.items()) return ( - f'[{thumb}' + f'[{thumb}' f'{title}' f"{description}]({page_ref}){{ .sq-card }}" ) @env.macro def show_members(cls_path: str) -> str: - """API sections for a widget: its Qt base class, signals, enums and methods.""" + """API of a widget: its class, Qt base class, signals, enums, and methods. + + The class's heading (anchored, and in `objects.inv`) heads the section. + """ module, name = cls_path.rsplit(".", 1) cls = getattr(import_module(module), name) qt_base = next((b for b in cls.__mro__ if _is_qt(b)), None) qt_members = {m for b in cls.__mro__ if _is_qt(b) for m in dir(b)} signals = dict(_signals(cls)) - out = ["## API\n"] + out = [_mkdocstrings_class(cls_path)] if qt_base is not None: link = f"[`{qt_base.__name__}`]({QT_DOCS.format(qt_base.__name__.lower())})" out.append( @@ -111,6 +122,19 @@ def show_members(cls_path: str) -> str: return "\n".join(out) +def _mkdocstrings_class(cls_path: str) -> str: + """The class's heading (level 2), signature, and docstring, without members.""" + options = """ + options: + heading_level: 2 + show_root_heading: true + show_root_toc_entry: true + members: false + overloads_only: true + """ + return f"::: {cls_path}\n{indent(dedent(options), ' ')}\n" + + def _mkdocstrings(cls_path: str, members: list[str]) -> str: options = f""" options: @@ -142,8 +166,7 @@ def _documented_overrides(cls: type, names: set[str]) -> set[str]: return out -@cache -def _manifest() -> dict[str, dict]: +def _manifest() -> dict[str, dict]: # (not cached: `zensical serve` may run long) return json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {} diff --git a/docs/_media.py b/docs/_media.py index e3eaf45e..32e62dac 100644 --- a/docs/_media.py +++ b/docs/_media.py @@ -1,7 +1,16 @@ -"""Offscreen renderer for the docs' widget screenshots and animations. +"""Renderer for the docs' widget screenshots and animations. Run it with `docs/_gen_media.py`; animations and capture options live in `docs/_scenes.py`. + +Widgets are drawn with one of two styles (`--style`): + +- `fusion` (default): Qt's Fusion style, with palettes that match the site, + rendered offscreen. Works anywhere, needs no display, and runs in parallel. +- `macos`: Qt's native macOS style, with the system's light and dark appearance. + Only on macOS, and with real windows: Qt's offscreen platform can't draw this + style, and windows that aren't shown are drawn as inactive. So the windows + appear on screen while they're rendered, one at a time. """ from __future__ import annotations @@ -21,8 +30,12 @@ from typing import TYPE_CHECKING, Any SCALE = 2 # device pixel ratio of the rendered images -os.environ["QT_QPA_PLATFORM"] = "offscreen" # deterministic, and headless -os.environ["QT_SCALE_FACTOR"] = str(SCALE) +STYLES = ("fusion", "macos") +STYLE = os.environ.get("SUPERQT_DOCS_STYLE", "fusion") # (set by `main` for workers) +_ENVIRON = dict(os.environ) # (for the workers, before it's changed here) +if STYLE == "fusion": + os.environ["QT_QPA_PLATFORM"] = "offscreen" # deterministic, and headless + os.environ["QT_SCALE_FACTOR"] = str(SCALE) from PIL import Image # noqa: E402 from qtpy import API_NAME, QT_VERSION, QtWidgets # noqa: E402 @@ -33,6 +46,7 @@ QRectF, QSize, Qt, + QTimer, qInstallMessageHandler, ) from qtpy.QtGui import ( # noqa: E402 @@ -45,6 +59,7 @@ QPainterPath, QPalette, QPen, + QPixmap, ) from qtpy.QtTest import QTest # noqa: E402 from qtpy.QtWidgets import QApplication, QWidget # noqa: E402 @@ -62,7 +77,8 @@ FPS = 30 FONTS = ("Inter", "Inter Variable", "Helvetica Neue", "Segoe UI", "Noto Sans") -# Fusion palettes, tuned to sit on the light and dark zensical "modern" theme. +# Fusion palettes, tuned to sit on the light and dark zensical "modern" theme +# (the macOS style uses the system's colors instead). # Keep `Highlight` in sync with `--sq-accent` in docs/stylesheets/extra.css. THEMES: dict[str, dict[str, str]] = { "light": { @@ -112,12 +128,16 @@ class Spec: width: int | None = None # resize the window to this width (logical px) height: int | None = None # ... and/or this height + # for continuous motion: no pause at the start or end, and frames at exact + # intervals, so that the last frame leads straight back into the first + seamless: bool = False setup: Callable[[QWidget], Any] | None = None # called before capturing scene: Callable[[Recorder, QWidget], Any] | None = None # records an animation def source(self) -> str: funcs = [f for f in (self.setup, self.scene) if f is not None] - return repr((self.width, self.height)) + "".join(map(inspect.getsource, funcs)) + sizes = (self.width, self.height, self.seamless) + return repr(sizes) + "".join(map(inspect.getsource, funcs)) SPECS: dict[str, Spec] = {} @@ -159,13 +179,26 @@ def _capture(main: QWidget, cursor: QPointF | None = None, pressed=False) -> Fra w for w in QApplication.topLevelWidgets() if w is not main and w.isVisible() ] windows = [ - (QRect(w.mapToGlobal(QPoint(0, 0)), w.size()), w.grab().toImage()) + (QRect(w.mapToGlobal(QPoint(0, 0)), w.size()), _grab(w)) for w in tops if w.isVisible() ] return Frame(windows, cursor, pressed, time.perf_counter()) +def _grab(widget: QWidget) -> QImage: + """Render a window at `SCALE`, whatever the pixel ratio of its screen.""" + pixmap = QPixmap(widget.size() * SCALE) + pixmap.setDevicePixelRatio(SCALE) + pixmap.fill(Qt.GlobalColor.transparent) + widget.render(pixmap) + return pixmap.toImage() + + +def _window_color() -> QColor: + return QApplication.palette().window().color() + + def _compose(frames: list[Frame], theme: str) -> list[QImage]: """Paint frames onto canvases with a common size (the union of all windows). @@ -184,13 +217,13 @@ def _compose(frames: list[Frame], theme: str) -> list[QImage]: ) bounds.adjust(-MARGIN, -MARGIN, MARGIN, MARGIN) - colors = THEMES[theme] + window_color = _window_color() backdrop, outline = (QColor(c) for c in BACKDROPS[theme]) images = [] for frame in frames: img = QImage(bounds.size() * SCALE, QImage.Format.Format_ARGB32_Premultiplied) img.setDevicePixelRatio(SCALE) - img.fill(QColor(colors["Window"]) if flat else backdrop) + img.fill(window_color if flat else backdrop) painter = QPainter(img) painter.setRenderHint(QPainter.RenderHint.Antialiasing) for i, (rect, win_img) in enumerate(frame.windows): @@ -198,7 +231,7 @@ def _compose(frames: list[Frame], theme: str) -> list[QImage]: if not flat: panel = rect.adjusted(-pad, -pad, pad, pad) if i == 0 else rect painter.fillRect(panel.translated(0, 2), QColor(0, 0, 0, 28)) # shadow - painter.fillRect(panel, QColor(colors["Window"])) + painter.fillRect(panel, window_color) painter.setPen(QPen(outline, 1)) painter.setBrush(Qt.BrushStyle.NoBrush) painter.drawRect(QRectF(panel).adjusted(-0.5, -0.5, 0.5, 0.5)) @@ -238,10 +271,14 @@ class Recorder: def __init__(self, window: QWidget, fps: int = FPS) -> None: self.window = window self.frames: list[Frame] = [] + self.inactive_frames = 0 + self.moved = False + self._origin = QPoint() self._interval = 1 / fps self._next = time.perf_counter() self._cursor: QPointF | None = None self._pressed = False + self._grab: QWidget | None = None # (the window that the button was pressed on) # -- primitives -- @@ -251,7 +288,13 @@ def frame(self) -> None: self._next = max(self._next + self._interval, time.perf_counter()) while (remaining := self._next - time.perf_counter()) > 0: QTest.qWait(max(1, int(remaining * 1000))) - self.frames.append(_capture(self.window, self._cursor, self._pressed)) + if not _ensure_active(self.window): + self.inactive_frames += 1 + frame = _capture(self.window, self._cursor, self._pressed) + if self.frames and frame.windows[0][0].topLeft() != self._origin: + self.moved = True # (by something else: real input, with the macos style) + self._origin = frame.windows[0][0].topLeft() + self.frames.append(frame) def wait(self, seconds: float) -> None: for _ in range(max(1, round(seconds / self._interval))): @@ -263,15 +306,35 @@ def _global(self, widget: QWidget | None, pos: QPoint | QPointF | None) -> QPoin pos = widget.rect().center() return QPointF(widget.mapToGlobal(QPointF(pos))) + def _window_at_cursor(self) -> QWidget | None: + """The window under the cursor: an open popup or modal dialog, or the window.""" + assert self._cursor is not None + pos = self._cursor.toPoint() + modal = QApplication.activeModalWidget() + windows = [QApplication.activePopupWidget(), modal, self.window] + for window in filter(None, windows): + if QRect(window.mapToGlobal(QPoint(0, 0)), window.size()).contains(pos): + return window + return None + def _send(self, kind: str) -> None: + """Send a mouse event to the window under the cursor (in its coordinates). + + While the button is pressed, events go to the window that it was pressed on. + """ assert self._cursor is not None - win = self.window.windowHandle() - origin = QPointF(self.window.mapToGlobal(QPoint(0, 0))) + under = self._window_at_cursor() + if kind == "press": + self._grab = under or self.window + target = self._grab if self._pressed or kind == "release" else under + if target is None: # (a move outside of the windows) + return + origin = QPointF(target.mapToGlobal(QPoint(0, 0))) local = (self._cursor - origin).toPoint() + win = target.windowHandle() btn, mod = Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier if kind == "move": - if self._pressed or self.window.rect().contains(local): - QTest.mouseMove(win, local) + QTest.mouseMove(win, local) elif kind == "press": QTest.mousePress(win, btn, mod, local) else: @@ -302,10 +365,11 @@ def press(self) -> None: self._send("press") self.wait(0.12) - def release(self) -> None: + def release(self, wait: float = 0.12) -> None: self._pressed = False self._send("release") - self.wait(0.12) + if wait: + self.wait(wait) def click(self, widget: QWidget | None = None, pos=None, **kwargs: Any) -> None: self.move(widget, pos, **kwargs) @@ -318,6 +382,30 @@ def drag(self, widget: QWidget | None, start, end, duration: float = 0.8) -> Non self.move(widget, end, duration) self.release() + def click_into_modal( + self, + widget: QWidget, + pos: QPoint | QPointF | None, + then: Callable[[QWidget], Any], + ) -> None: + """Click something that opens a modal dialog, and record `then(dialog)`. + + A modal dialog runs its own event loop (`exec()`) inside the click, so `then` + runs (and records) inside that loop. It should close the dialog. + """ + + def _in_dialog() -> None: + if (dialog := QApplication.activeModalWidget()) is None: + QTimer.singleShot(10, _in_dialog) # (not open yet) + return + QTest.qWaitForWindowExposed(dialog) + then(dialog) + + self.move(widget, pos) + self.press() + QTimer.singleShot(0, _in_dialog) + self.release() + def type(self, widget: QWidget, text: str, interval: float = 0.09) -> None: widget.setFocus() for char in text: @@ -418,6 +506,17 @@ def _run_example(name: str) -> tuple[QWidget, dict]: return shown[0], namespace +def _ensure_active(window: QWidget, timeout: int = 1000) -> bool: + """With the macos style, make `window` active (inactive windows are gray).""" + if STYLE != "macos" or window.isActiveWindow(): + return True + if QApplication.activePopupWidget() or QApplication.activeModalWidget(): + return True # (a popup, or a dialog, of the window has the focus) + window.raise_() + window.activateWindow() + return QTest.qWaitForWindowActive(window, timeout) + + def _clear_focus() -> None: if widget := QApplication.focusWidget(): widget.clearFocus() @@ -438,6 +537,9 @@ def _qt_message_handler(mode: Any, context: Any, message: str) -> None: def _make_app() -> QApplication: qInstallMessageHandler(_qt_message_handler) app = QApplication([]) + if STYLE == "macos": + app.setStyle("macos") # (with the system font) + return app app.setStyle("Fusion") families = set(QFontDatabase.families()) if family := next((f for f in FONTS if f in families), None): @@ -446,6 +548,15 @@ def _make_app() -> QApplication: def _set_theme(theme: str) -> None: + hints = QGuiApplication.styleHints() + if hasattr(hints, "setColorScheme"): # Qt >= 6.8 + scheme = Qt.ColorScheme.Dark if theme == "dark" else Qt.ColorScheme.Light + hints.setColorScheme(scheme) + elif STYLE == "macos": + raise RuntimeError("the macos style needs Qt >= 6.8, to switch themes") + if STYLE == "macos": + return # (the style uses the system's colors for the scheme) + colors = THEMES[theme] palette = QPalette(QColor(colors["Button"]), QColor(colors["Window"])) for role, color in colors.items(): @@ -468,9 +579,6 @@ def _set_theme(theme: str) -> None: pen_inactive=accent.darker(125).name(), pen_disabled=colors["PlaceholderText"], ) - if hasattr(hints := QGuiApplication.styleHints(), "setColorScheme"): - scheme = Qt.ColorScheme.Dark if theme == "dark" else Qt.ColorScheme.Light - hints.setColorScheme(scheme) def _to_pil(img: QImage) -> Image.Image: @@ -482,19 +590,25 @@ def _to_pil(img: QImage) -> Image.Image: return Image.frombuffer("RGBA", size, bytes(ptr), "raw", "RGBA", 0, 1) -def _save_animation(frames: list[Frame], images: list[QImage], dest: Path) -> None: +def _save_animation( + frames: list[Frame], images: list[QImage], dest: Path, seamless: bool = False +) -> None: pils: list[Image.Image] = [] durations: list[int] = [] - times = [f.t for f in frames] + [frames[-1].t + 1 / FPS] + if seamless: + times = [i / FPS for i in range(len(frames) + 1)] + else: + times = [f.t for f in frames] + [frames[-1].t + 1 / FPS] for i, img in enumerate(images): pil = _to_pil(img).convert("RGB") - ms = round((times[i + 1] - times[i]) * 1000) + ms = round(times[i + 1] * 1000) - round(times[i] * 1000) # (no drift) if pils and pil.tobytes() == pils[-1].tobytes(): durations[-1] += ms # merge repeated frames else: pils.append(pil) durations.append(ms) - durations[-1] += 1200 # rest on the last frame before looping + if not seamless: + durations[-1] += 1200 # rest on the last frame before looping pils[0].save( dest, save_all=True, @@ -506,35 +620,54 @@ def _save_animation(frames: list[Frame], images: list[QImage], dest: Path) -> No ) +def _resize(window: QWidget, width: int | None, height: int | None) -> None: + """Resize to `width` and/or `height` (if only width: the height that fits).""" + if not (width or height): + return + width = width or window.width() + height = height or window.heightForWidth(width) + if height <= 0: + height = window.sizeHint().height() + window.resize(width, height) + + def _render(name: str, theme: str) -> dict[str, Any]: """Render one example in one theme (in a fresh process: see `_work`).""" _set_theme(theme) spec = SPECS.get(name, Spec()) window, _namespace = _run_example(name) # (keeps the example's objects alive) if spec.width or spec.height: - width = spec.width or window.width() - height = spec.height or window.heightForWidth(width) - if height <= 0: - height = window.sizeHint().height() - window.resize(width, height) + _resize(window, spec.width, spec.height) if spec.setup is not None: spec.setup(window) _clear_focus() # no text cursor or focus ring in stills QTest.qWait(50) + if not _ensure_active(window, 3000): + print(f"warning: {name}'s window wasn't active", file=sys.stderr) still = _compose([_capture(window)], theme)[0] _to_pil(still).save(OUT / f"{name}-{theme}.png", optimize=True) info: dict[str, Any] = { "width": still.width() // SCALE, "height": still.height() // SCALE, + "background": _window_color().name(), } if spec.scene is not None: rec = Recorder(window) - rec.wait(0.8) + if not spec.seamless: + rec.wait(0.5) spec.scene(rec, window) - rec.wait(0.3) + if not spec.seamless: + rec.wait(0.6) + if rec.moved: + print(f"warning: {name}'s window moved while recording", file=sys.stderr) + if rec.inactive_frames: + n = rec.inactive_frames + print( + f"warning: {name}'s window was inactive in {n} frames", file=sys.stderr + ) images = _compose(rec.frames, theme) - _save_animation(rec.frames, images, OUT / f"{name}-{theme}.webp") + _save_animation(rec.frames, images, OUT / f"{name}-{theme}.webp", spec.seamless) info["animation"] = { "width": images[0].width() // SCALE, "height": images[0].height() // SCALE, @@ -558,21 +691,22 @@ def _work(name: str, theme: str) -> None: _RESULT = "@@result " -def _run_job(name: str, theme: str) -> tuple[dict | None, str]: +def _run_job(name: str, theme: str, style: str) -> tuple[dict | None, str]: cmd = [sys.executable, str(DOCS / "_gen_media.py"), "--worker", name, theme] - proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + env = {**_ENVIRON, "SUPERQT_DOCS_STYLE": style} + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180, env=env) for line in proc.stdout.splitlines(): if line.startswith(_RESULT): return json.loads(line[len(_RESULT) :]), proc.stderr return None, proc.stderr or f"exited with {proc.returncode}" -def _hash(name: str) -> str: +def _hash(name: str, style: str) -> str: src = [ (EXAMPLES / f"{name}.py").read_text(), Path(__file__).read_text(), SPECS.get(name, Spec()).source(), - f"{API_NAME} {QT_VERSION}", + f"{API_NAME} {QT_VERSION} {style}", ] return hashlib.sha256("\0".join(src).encode()).hexdigest()[:16] @@ -587,10 +721,25 @@ def main(argv: list[str] | None = None, description: str = "") -> int: parser.add_argument("names", nargs="*", help="examples to render (default: all)") parser.add_argument("-f", "--force", action="store_true", help="ignore the cache") parser.add_argument("-j", "--jobs", type=int, default=os.cpu_count()) + parser.add_argument( + "-s", + "--style", + choices=STYLES, + default="fusion", + help="Qt style to draw the widgets with (default: fusion; see _media.py)", + ) parser.add_argument("--worker", nargs=2, help=argparse.SUPPRESS) args = parser.parse_args(argv) if args.worker: _work(*args.worker) + if args.style == "macos": + if sys.platform != "darwin": + parser.error("the macos style is only available on macOS") + args.jobs = 1 # (only one window can be active at a time) + print( + "Rendering with the macos style: windows will appear on screen.\n" + "Don't move the mouse over them, or type, until it's done." + ) import _scenes # noqa: F401 (registers specs) @@ -605,16 +754,17 @@ def main(argv: list[str] | None = None, description: str = "") -> int: name for name in args.names or available if args.force - or manifest.get(name, {}).get("hash") != _hash(name) + or manifest.get(name, {}).get("hash") != _hash(name, args.style) or not _outputs_exist(name, manifest[name]) ] print(f"rendering {len(todo)} of {len(args.names or available)} examples") t0 = time.perf_counter() failed: set[str] = set() - jobs = {(name, theme) for name in todo for theme in THEMES} + results: dict[str, dict[str, dict]] = {} + jobs = [(name, theme) for name in todo for theme in THEMES] with ThreadPoolExecutor(max_workers=args.jobs) as pool: - futures = {pool.submit(_run_job, *job): job for job in jobs} + futures = {pool.submit(_run_job, *job, args.style): job for job in jobs} for future in as_completed(futures): (name, theme), (info, stderr) = futures[future], future.result() if info is None: @@ -622,9 +772,23 @@ def main(argv: list[str] | None = None, description: str = "") -> int: print(f" ✗ {name} ({theme})\n{stderr}", file=sys.stderr) continue print(f" ✓ {name} ({theme})") - if theme == "light": - manifest[name] = {"hash": _hash(name), **info} - + for line in stderr.splitlines(): + if line.startswith("warning:"): + print(f" {line}") + results.setdefault(name, {})[theme] = info + + for name, infos in results.items(): + if name in failed: + manifest.pop(name, None) + continue + # sizes are the same in both themes; the window color isn't + backgrounds = {theme: info.pop("background") for theme, info in infos.items()} + manifest[name] = { + "hash": _hash(name, args.style), + "style": args.style, + **infos["light"], + "background": backgrounds, + } for name in failed: manifest.pop(name, None) MANIFEST.write_text(json.dumps(dict(sorted(manifest.items())), indent=2) + "\n") diff --git a/docs/_scenes.py b/docs/_scenes.py index d90b51ec..038f5e1f 100644 --- a/docs/_scenes.py +++ b/docs/_scenes.py @@ -8,11 +8,18 @@ from __future__ import annotations +import gc from typing import TYPE_CHECKING -from _media import scene, spec +from _media import FPS, scene, spec from qtpy.QtCore import QPoint, Qt -from qtpy.QtWidgets import QComboBox, QSlider, QStyle, QStyleOptionSlider +from qtpy.QtWidgets import ( + QComboBox, + QDialogButtonBox, + QSlider, + QStyle, + QStyleOptionSlider, +) from superqt import ( QColormapComboBox, @@ -20,6 +27,8 @@ QSearchableComboBox, QToggleSwitch, ) +from superqt.fonticon import Animation +from superqt.utils import signals_blocked if TYPE_CHECKING: from _media import Recorder @@ -67,13 +76,45 @@ def _single_scene(r: Recorder, window: QWidget) -> None: r.leave() -SLIDER_WIDTH = 480 +def _edit_label(r: Recorder, label: QWidget, text: str) -> None: + """Type a value into a slider's label (a line edit), and press Enter.""" + r.click(label) + label.selectAll() + r.leave(duration=0.3) + r.type(label, text) + r.wait(0.3) + r.key(label, Qt.Key.Key_Return) + r.wait(0.8) + + +def _labeled_single_scene(r: Recorder, window: QWidget) -> None: + # drag the handle, then type the value it started at into the label + initial = window.value() + _drag_handle(r, window._slider, 0, 0.3) + _edit_label(r, window._label, f"{initial:g}") + + +def _labeled_range_scene(r: Recorder, window: QWidget) -> None: + # drag a handle and the bar, then type the upper handle's start value in its label + initial = window.value() + slider = window._slider + _drag_handle(r, slider, 0, 0.25) + bar = (_handle(slider, 0) + _handle(slider, 1)) / 2 + r.drag(slider, bar, bar - QPoint(round(slider.width() * 0.25), 0), duration=0.8) + r.wait(0.3) + _edit_label(r, window._handle_labels[-1], f"{initial[-1]:g}") + window.setValue(initial) # (in case the drags rounded the lower value) + + +# (narrow enough that the gallery cards don't shrink them much) +SLIDER = {"width": 360} for name in ("qrangeslider", "qdoublerangeslider"): - spec(name, width=SLIDER_WIDTH, scene=_range_scene) + spec(name, scene=_range_scene, **SLIDER) +spec("qdoubleslider", scene=_single_scene, **SLIDER) for name in ("qlabeledrangeslider", "qlabeleddoublerangeslider"): - spec(name, width=SLIDER_WIDTH, scene=_range_scene) -for name in ("qdoubleslider", "qlabeledslider", "qlabeleddoubleslider"): - spec(name, width=SLIDER_WIDTH, scene=_single_scene) + spec(name, scene=_labeled_range_scene, **SLIDER) +for name in ("qlabeledslider", "qlabeleddoubleslider"): + spec(name, scene=_labeled_single_scene, **SLIDER) # --------------------------------------------------------------------------- @@ -108,9 +149,36 @@ def _(r: Recorder, window: QWidget) -> None: r.wait(0.3) -@scene("fonticon_animation") +@scene("fonticon_animation", seamless=True) def _(r: Recorder, window: QWidget) -> None: - r.wait(2.4) + # Step the animations by frame number, not by their timers, for 14.4 s: a whole + # number of turns of both (spin: 1° per 10 ms; pulse: 45° per 200 ms), so the + # loop is seamless. + animations = [obj for obj in gc.get_objects() if isinstance(obj, Animation)] + rates = [(anim._step, anim.timer.interval()) for anim in animations] + for anim in animations: + anim.timer.setInterval( + 2**31 - 1 + ) # (still active, so `animate` won't restart it) + for i in range(round(14.4 * FPS)): + for anim, (step, interval) in zip(animations, rates, strict=True): + anim._angle = step * (i * 1000 // (FPS * interval)) + anim.parent_widget.update() + r.frame() + + +@scene("qcolormaplineedit", width=260) +def _(r: Recorder, window: QWidget) -> None: + # the swatch follows the text: the fallback until the name is a colormap + r.click(window) + window.selectAll() + r.leave(duration=0.3) + r.type(window, "magma", interval=0.15) + r.wait(1.0) + window.selectAll() + r.type(window, "viridis", interval=0.15) + r.wait(0.4) + window.clearFocus() @scene("qelidinglabel", width=300) @@ -140,7 +208,7 @@ def _(r: Recorder, window: QWidget) -> None: r.key(window.filter_widget, Qt.Key.Key_Backspace, times=3) -@scene("qsearchabletreewidget", width=320, height=260) +@scene("qsearchabletreewidget", width=320, height=380) def _(r: Recorder, window: QWidget) -> None: r.click(window.filter) r.leave(duration=0.3) @@ -151,20 +219,28 @@ def _(r: Recorder, window: QWidget) -> None: @scene("qsearchablecombobox", width=200) def _(r: Recorder, window: QComboBox) -> None: - edit = window.lineEdit() - r.click(edit) - edit.selectAll() - r.leave(duration=0.3) - r.type(edit, "baz") - r.wait(0.6) - _complete(r, window) + _search(r, window, "baz") r.wait(1.0) window.setCurrentIndex(0) - edit.clearFocus() + window.lineEdit().clearFocus() -def _complete(r: Recorder, combo: QComboBox) -> None: - """Pick the first completion, with the keyboard.""" +@scene("colormap_catalog", width=220) +def _(r: Recorder, window: QComboBox) -> None: + _search(r, window, "ice") + r.wait(1.0) + window.setCurrentText("viridis") + window.lineEdit().clearFocus() + + +def _search(r: Recorder, combo: QComboBox, text: str) -> None: + """Type into an editable combo box, and pick the first completion.""" + edit = combo.lineEdit() + r.click(edit) + edit.selectAll() + r.leave(duration=0.3) + r.type(edit, text) + r.wait(0.6) popup = combo.completer().popup() r.key(popup, Qt.Key.Key_Down, interval=0.3) r.key(popup, Qt.Key.Key_Return) @@ -174,7 +250,7 @@ def _complete(r: Recorder, combo: QComboBox) -> None: # Combo boxes: open the popup and pick an item -def _pick(r: Recorder, combo: QComboBox, index: int) -> None: +def _pick(r: Recorder, combo: QComboBox, index: int, restore: bool = True) -> None: initial = combo.currentIndex() r.click(combo) r.wait(0.3) @@ -184,8 +260,9 @@ def _pick(r: Recorder, combo: QComboBox, index: int) -> None: r.press() r.release() r.wait(0.8) - r.leave() - combo.setCurrentIndex(initial) + if restore: + r.leave() + combo.setCurrentIndex(initial) @scene("qenumcombobox", width=200) @@ -202,8 +279,56 @@ def _(r: Recorder, window: QComboBox) -> None: def _(r: Recorder, window: QComboBox) -> None: _pick(r, window, 2) + # then add one from the catalog, with "Add Colormap..." (a dialog) + def in_dialog(dialog: QWidget) -> None: + _search(r, dialog.combo, "ice") + r.wait(0.6) + buttons = dialog.findChild(QDialogButtonBox) + r.move(buttons.button(QDialogButtonBox.StandardButton.Ok)) + r.press() + r.release(wait=0) # (so that the dialog's `exec()` returns at once) -spec("colormap_catalog", width=220) + r.click(window) + r.wait(0.3) + view = window.view() + add = view.visualRect(window.model().index(window.count() - 1, 0)) + r.click_into_modal(view, add.center(), in_dialog) + r.wait(1.2) + r.leave() + # back to the start, for the next loop + window.removeItem(window.currentIndex()) + window.setCurrentIndex(0) + + +# --------------------------------------------------------------------------- +# Throttling + + +@scene("throttling", width=520) +def _(r: Recorder, window: QWidget) -> None: + slider = window.findChild(QSlider) + initial = slider.value() + start = _handle(slider, 0) + r.drag(slider, start, start + QPoint(round(slider.width() * 0.5), 0), duration=1.8) + r.wait(1.0) + here = _handle(slider, 0) + r.drag(slider, here, start, duration=1.8) + r.leave() + with signals_blocked(slider): + slider.setValue(initial) # (in case the drags rounded it) + r.wait(4.2) # until the ticks have scrolled off, so the loop is seamless + + +# --------------------------------------------------------------------------- +# Icons + + +@scene("iconify_states") +def _(r: Recorder, window: QWidget) -> None: + r.click(window) + r.wait(1.0) + r.click(window, duration=0.2) + r.leave() # --------------------------------------------------------------------------- @@ -222,13 +347,7 @@ def _(r: Recorder, window: QWidget) -> None: cmap.setCurrentIndex(1) r.click(switch, QPoint(14, switch.height() // 2)) r.wait(0.3) - edit = channel.lineEdit() - r.click(edit) - edit.selectAll() - r.leave(duration=0.3) - r.type(edit, "ch") - r.wait(0.6) - _complete(r, channel) + _search(r, channel, "ch") r.wait(1.0) # back to the start, for the next loop for widget in (channel, cmap): @@ -236,7 +355,7 @@ def _(r: Recorder, window: QWidget) -> None: limits.setValue((30, 200)) switch.setChecked(False) channel.completer().popup().hide() - edit.clearFocus() + channel.lineEdit().clearFocus() r.wait(0.1) @@ -244,5 +363,15 @@ def _(r: Recorder, window: QWidget) -> None: # Stills spec("qlargeintspinbox", width=180) -spec("qquantity", width=220) + + +@scene("qquantity", width=220) +def _(r: Recorder, window: QWidget) -> None: + # changing the units converts the value: 1 m, 1000 mm, 0.001 km, 1 m + combo = window.unitsComboBox() + for unit in ("mm", "km", "m"): + _pick(r, combo, combo.findText(unit), restore=False) + r.leave() + + spec("code_syntax_highlight", width=460, height=260) diff --git a/docs/examples/fonticon_animation.py b/docs/examples/fonticon_animation.py index ddc097e5..6faa954f 100644 --- a/docs/examples/fonticon_animation.py +++ b/docs/examples/fonticon_animation.py @@ -1,4 +1,5 @@ from fonticon_fa5 import FA5S +from qtpy.QtGui import QPalette from qtpy.QtWidgets import QApplication, QHBoxLayout, QPushButton, QWidget from superqt.fonticon import icon, pulse, spin @@ -7,13 +8,14 @@ window = QWidget() layout = QHBoxLayout(window) +color = window.palette().color(QPalette.ColorRole.ButtonText).name() # (dark themes) spinning = QPushButton("spin") -spinning.setIcon(icon(FA5S.sync, animation=spin(spinning))) +spinning.setIcon(icon(FA5S.sync, color=color, animation=spin(spinning))) layout.addWidget(spinning) pulsing = QPushButton("pulse") -pulsing.setIcon(icon(FA5S.spinner, animation=pulse(pulsing))) +pulsing.setIcon(icon(FA5S.spinner, color=color, animation=pulse(pulsing))) layout.addWidget(pulsing) window.show() diff --git a/docs/examples/iconify_color.py b/docs/examples/iconify_color.py new file mode 100644 index 00000000..da96476f --- /dev/null +++ b/docs/examples/iconify_color.py @@ -0,0 +1,15 @@ +from qtpy.QtCore import QSize +from qtpy.QtWidgets import QApplication, QPushButton + +from superqt import QIconifyIcon + +app = QApplication([]) + +button = QPushButton() +# --8<-- [start:icon] +button.setIcon(QIconifyIcon("bi:bell-fill", color="red", rotate=90)) +# --8<-- [end:icon] +button.setIconSize(QSize(48, 48)) +button.show() + +app.exec() diff --git a/docs/examples/iconify_palette.py b/docs/examples/iconify_palette.py new file mode 100644 index 00000000..efe2f174 --- /dev/null +++ b/docs/examples/iconify_palette.py @@ -0,0 +1,15 @@ +from qtpy.QtGui import QPalette +from qtpy.QtWidgets import QApplication, QPushButton + +from superqt import QIconifyIcon + +app = QApplication([]) + +button = QPushButton("Notifications") +# --8<-- [start:icon] +color = button.palette().color(QPalette.ColorRole.ButtonText).name() +button.setIcon(QIconifyIcon("bi:bell", color=color)) +# --8<-- [end:icon] +button.show() + +app.exec() diff --git a/docs/examples/iconify_states.py b/docs/examples/iconify_states.py new file mode 100644 index 00000000..a9576442 --- /dev/null +++ b/docs/examples/iconify_states.py @@ -0,0 +1,17 @@ +from qtpy.QtGui import QIcon +from qtpy.QtWidgets import QApplication, QPushButton + +from superqt import QIconifyIcon + +app = QApplication([]) + +button = QPushButton("Notifications") +# --8<-- [start:icon] +icon = QIconifyIcon("bi:bell", color="gray") +icon.addKey("bi:bell-fill", color="orange", state=QIcon.State.On) +button.setCheckable(True) +button.setIcon(icon) +# --8<-- [end:icon] +button.show() + +app.exec() diff --git a/docs/examples/qcolormap.py b/docs/examples/qcolormap.py index 6c6754f4..9aa5c39a 100644 --- a/docs/examples/qcolormap.py +++ b/docs/examples/qcolormap.py @@ -5,7 +5,8 @@ app = QApplication([]) -cmap_combo = QColormapComboBox() +# (allow_user_colormaps adds an "Add Colormap..." item, to choose from the catalog) +cmap_combo = QColormapComboBox(allow_user_colormaps=True) # see note above about colormap-like objects # as names from the cmap catalog cmap_combo.addColormaps(["viridis", "plasma", "magma", "gray"]) diff --git a/docs/examples/qcolormaplineedit.py b/docs/examples/qcolormaplineedit.py new file mode 100644 index 00000000..30b72aed --- /dev/null +++ b/docs/examples/qcolormaplineedit.py @@ -0,0 +1,11 @@ +from qtpy.QtWidgets import QApplication + +from superqt.cmap import QColormapLineEdit + +app = QApplication([]) + +line_edit = QColormapLineEdit() +line_edit.setText("viridis") +line_edit.show() + +app.exec() diff --git a/docs/examples/qsearchabletreewidget.py b/docs/examples/qsearchabletreewidget.py index 3bc2e429..7a15026c 100644 --- a/docs/examples/qsearchabletreewidget.py +++ b/docs/examples/qsearchabletreewidget.py @@ -16,6 +16,7 @@ }, } tree = QSearchableTreeWidget.fromData(data) +tree.tree.expandAll() tree.show() app.exec() diff --git a/docs/examples/showcase.py b/docs/examples/showcase.py index f0dfe65b..60f3e399 100644 --- a/docs/examples/showcase.py +++ b/docs/examples/showcase.py @@ -13,6 +13,7 @@ panel = QWidget() form = QFormLayout(panel) +form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) channel = QSearchableComboBox() channel.addItems(["DAPI", "GFP", "mCherry", "Cy5", "Brightfield"]) diff --git a/docs/examples/throttling.py b/docs/examples/throttling.py new file mode 100644 index 00000000..e53d44fe --- /dev/null +++ b/docs/examples/throttling.py @@ -0,0 +1,93 @@ +"""A slider's valueChanged, connected directly, throttled, and debounced. + +Drag the slider: each lane of the timeline draws a tick for each call (newest on +the right), and shows the value that the last call received. (Inspired by +examples/throttler_demo.py, which is adapted from KDAB's KDToolBox.) +""" + +import time +from collections import deque + +from qtpy.QtCore import QPointF, QRectF, QSize, Qt, QTimer +from qtpy.QtGui import QColor, QPainter, QPen +from qtpy.QtWidgets import QApplication, QSlider, QVBoxLayout, QWidget + +from superqt.utils import qdebounced, qthrottled + +SPEED = 100 # pixels per second +LABEL_WIDTH = 170 + + +class Timeline(QWidget): + """Lanes of ticks that scroll to the left, one lane per kind of call.""" + + def __init__(self, lanes: dict[str, str]) -> None: + super().__init__() + self._colors = lanes # lane name -> tick color + self._ticks = {name: deque() for name in lanes} + self._values = dict.fromkeys(lanes, "") + self._timer = QTimer(self, interval=16, timeout=self.update) + self._timer.start() + + def sizeHint(self) -> QSize: + return QSize(480, 150) + + def add(self, lane: str, value: int) -> None: + self._ticks[lane].append(time.perf_counter()) + self._values[lane] = str(value) + + def paintEvent(self, event) -> None: + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + palette = self.palette() + painter.fillRect(self.rect(), palette.base()) + now, height = time.perf_counter(), self.height() / len(self._ticks) + for i, (lane, ticks) in enumerate(self._ticks.items()): + top = i * height + # the lane's name, and the last value it received + painter.setPen(palette.text().color()) + label = QRectF(10, top, LABEL_WIDTH - 20, height) + align = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter + painter.drawText(label, align, f"{lane}\n{self._values[lane]}") + # a tick for each call + painter.setPen(QPen(QColor(self._colors[lane]), 2)) + for t in ticks: + x = self.width() - (now - t) * SPEED + painter.drawLine(QPointF(x, top + 8), QPointF(x, top + height - 8)) + while ticks and self.width() - (now - ticks[0]) * SPEED < LABEL_WIDTH: + ticks.popleft() + + +app = QApplication([]) + +window = QWidget() +slider = QSlider(Qt.Orientation.Horizontal) +slider.setValue(20) +timeline = Timeline( + { + "valueChanged": "#8c8c8c", + "qthrottled (100 ms)": "#3b82f6", + "qdebounced (300 ms)": "#f59e0b", + } +) +layout = QVBoxLayout(window) +layout.addWidget(slider) +layout.addWidget(timeline) + + +@qthrottled(timeout=100) +def throttled(value: int) -> None: + timeline.add("qthrottled (100 ms)", value) + + +@qdebounced(timeout=300) +def debounced(value: int) -> None: + timeline.add("qdebounced (300 ms)", value) + + +slider.valueChanged.connect(lambda value: timeline.add("valueChanged", value)) +slider.valueChanged.connect(throttled) +slider.valueChanged.connect(debounced) + +window.show() +app.exec() diff --git a/docs/faq.md b/docs/faq.md index 67cbe52b..9f4e444f 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -27,3 +27,9 @@ the following: slider.setStyleSheet(MONTEREY_SLIDER_STYLES_FIX) ``` + +::: superqt.sliders.MONTEREY_SLIDER_STYLES_FIX + options: + heading_level: 3 + show_if_no_docstring: true + show_attribute_values: false diff --git a/docs/images/logo-dark.svg b/docs/images/logo-dark.svg new file mode 100644 index 00000000..5a1a785d --- /dev/null +++ b/docs/images/logo-dark.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/images/logo.svg b/docs/images/logo.svg new file mode 100644 index 00000000..85d23ed4 --- /dev/null +++ b/docs/images/logo.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/index.md b/docs/index.md index 3d054b4a..cef65be8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -7,7 +7,7 @@ hide:
-# superqt +# ![](images/logo.svg#only-light){ .sq-logo }![](images/logo-dark.svg#only-dark){ .sq-logo } superqt

"Missing" widgets and components for PyQt and PySide.

@@ -60,30 +60,43 @@ Some features need extra dependencies, which can also be installed as extras: | --- | --- | --- | | `cmap` | [cmap](https://cmap-docs.readthedocs.io/) | [`QColormapComboBox`](widgets/qcolormap.md), [`CmapCatalogComboBox`](widgets/colormap_catalog.md), [colormap utilities](utilities/cmap.md) | | `quantity` | [pint](https://pint.readthedocs.io/) | [`QQuantity`](widgets/qquantity.md) | -| `iconify` | [pyconify](https://github.com/pyapp-kit/pyconify) | [`QIconifyIcon`](utilities/iconify.md) | -| `font-fa5`, `font-fa6` | Font Awesome 5 or 6 | [font icons](utilities/fonticon.md) | -| `font-mi6`, `font-mi7` | Material Design Icons 6 or 7 | [font icons](utilities/fonticon.md) | +| `iconify` | [pyconify](https://github.com/pyapp-kit/pyconify) | [`QIconifyIcon`](utilities/icons/iconify.md) | +| `font-fa5`, `font-fa6` | Font Awesome 5 or 6 | [font icons](utilities/icons/fonticon.md) | +| `font-mi6`, `font-mi7` | Material Design Icons 6 or 7 | [font icons](utilities/icons/fonticon.md) | superqt is tested on macOS, Windows, and Linux, with Python 3.11 and later, and with PyQt5 (5.15), PyQt6, and PySide6. ## Widgets -