diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..7ded7400 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,67 @@ +name: Docs + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + build: + # screenshots are rendered with the native macOS style (in real windows) + runs-on: macos-latest + 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" + + - name: Render screenshots and animations + run: uv run --group docs python docs/_gen_media.py --style macos + + - name: Build + run: | + uv run --group docs zensical build --clean --strict + touch site/.nojekyll + + # for docs-preview.yml, which deploys PR builds (it can't see the PR number) + - if: github.event_name == 'pull_request' + run: echo "${{ github.event.number }}" > pr-number + + - uses: actions/upload-artifact@v7 + with: + name: site + path: | + site + pr-number + include-hidden-files: true # (.nojekyll) + + # zensical has no gh-deploy; push the built site to the gh-pages branch + # (keeping the PR previews, which docs-preview.yml puts in pr-preview/) + deploy: + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v8 + with: + name: site + - uses: JamesIves/github-pages-deploy-action@v4 + with: + folder: site + clean-exclude: pr-preview/ 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..b9202e46 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,4 +48,32 @@ 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 + +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 +``` + +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. The +published docs are rendered this way, on a macOS runner in CI. + +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/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/_gen_media.py b/docs/_gen_media.py new file mode 100644 index 00000000..10980b78 --- /dev/null +++ b/docs/_gen_media.py @@ -0,0 +1,20 @@ +"""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 + uv run --group docs python docs/_gen_media.py --style macos # native, on macOS +""" + +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..346b68e4 100644 --- a/docs/_macros.py +++ b/docs/_macros.py @@ -1,136 +1,237 @@ +"""Macros for the superqt docs (see `[project.plugins.macros]` in zensical.toml).""" + +from __future__ import annotations + +import ast +import inspect +import json +import os import sys from enum import EnumMeta 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([])" - ) - 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" + 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: + msg = _missing(name) + 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) + 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 = style = "" + if (info := _manifest().get(name)) is None: + _missing(name) + else: + root = "../" * Path(page.path).as_posix().count("/") + "_generated/" + # 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}.{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'{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 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 = [_mkdocstrings_class(cls_path)] + 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_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: + 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 + + +def _missing(name: str) -> str: + """Raise in CI, else warn (so that `zensical serve` keeps running).""" + msg = f"No screenshot of `{name}` yet: run `docs/_gen_media.py`." + if os.environ.get("CI"): # (`--strict` ignores the warnings of macros) + raise RuntimeError(msg) + print(f"warning: {msg}", file=sys.stderr) + return msg + + +def _manifest() -> dict[str, dict]: # (not cached: `zensical serve` may run long) + 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..32e62dac --- /dev/null +++ b/docs/_media.py @@ -0,0 +1,796 @@ +"""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 + +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 +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 +from qtpy.QtCore import ( # noqa: E402 + QPoint, + QPointF, + QRect, + QRectF, + QSize, + Qt, + QTimer, + qInstallMessageHandler, +) +from qtpy.QtGui import ( # noqa: E402 + QColor, + QFont, + QFontDatabase, + QGuiApplication, + QImage, + QPainter, + QPainterPath, + QPalette, + QPen, + QPixmap, +) +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 +# (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": { + "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 + # 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] + sizes = (self.width, self.height, self.seamless) + return repr(sizes) + "".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()), _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). + + 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) + + 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(window_color 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, 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)) + 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.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 -- + + 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))) + 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))): + 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 _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 + 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": + 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, wait: float = 0.12) -> None: + self._pressed = False + self._send("release") + if wait: + self.wait(wait) + + 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 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: + 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 _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() + + +# --------------------------------------------------------------------------- +# 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([]) + 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): + app.setFont(QFont(family, 10)) + return app + + +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(): + 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"], + ) + + +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, seamless: bool = False +) -> None: + pils: list[Image.Image] = [] + durations: list[int] = [] + 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] * 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) + if not seamless: + 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 _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: + _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) + if not spec.seamless: + rec.wait(0.5) + spec.scene(rec, window) + 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", spec.seamless) + 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, style: str) -> tuple[dict | None, str]: + cmd = [sys.executable, str(DOCS / "_gen_media.py"), "--worker", name, theme] + 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, style: str) -> str: + src = [ + (EXAMPLES / f"{name}.py").read_text(), + Path(__file__).read_text(), + SPECS.get(name, Spec()).source(), + f"{API_NAME} {QT_VERSION} {style}", + ] + 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( + "-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) + + 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, 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() + 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, 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: + failed.add(name) + print(f" ✗ {name} ({theme})\n{stderr}", file=sys.stderr) + continue + print(f" ✓ {name} ({theme})") + 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") + 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..038f5e1f --- /dev/null +++ b/docs/_scenes.py @@ -0,0 +1,377 @@ +"""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 + +import gc +from typing import TYPE_CHECKING + +from _media import FPS, scene, spec +from qtpy.QtCore import QPoint, Qt +from qtpy.QtWidgets import ( + QComboBox, + QDialogButtonBox, + QSlider, + QStyle, + QStyleOptionSlider, +) + +from superqt import ( + QColormapComboBox, + QLabeledRangeSlider, + QSearchableComboBox, + QToggleSwitch, +) +from superqt.fonticon import Animation +from superqt.utils import signals_blocked + +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() + + +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, scene=_range_scene, **SLIDER) +spec("qdoubleslider", scene=_single_scene, **SLIDER) +for name in ("qlabeledrangeslider", "qlabeleddoublerangeslider"): + spec(name, scene=_labeled_range_scene, **SLIDER) +for name in ("qlabeledslider", "qlabeleddoubleslider"): + spec(name, scene=_labeled_single_scene, **SLIDER) + + +# --------------------------------------------------------------------------- +# Buttons, containers and layouts + + +@scene("qtoggleswitch", width=170) +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("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", seamless=True) +def _(r: Recorder, window: QWidget) -> None: + # 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) +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=380) +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: + _search(r, window, "baz") + r.wait(1.0) + window.setCurrentIndex(0) + window.lineEdit().clearFocus() + + +@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) + + +# --------------------------------------------------------------------------- +# Combo boxes: open the popup and pick an item + + +def _pick(r: Recorder, combo: QComboBox, index: int, restore: bool = True) -> 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) + if restore: + 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) + + # 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) + + 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() + + +# --------------------------------------------------------------------------- +# 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) + _search(r, channel, "ch") + 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() + channel.lineEdit().clearFocus() + r.wait(0.1) + + +# --------------------------------------------------------------------------- +# Stills + +spec("qlargeintspinbox", width=180) + + +@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/code_syntax_highlight.py b/docs/examples/code_syntax_highlight.py new file mode 100644 index 00000000..c9ccd26a --- /dev/null +++ b/docs/examples/code_syntax_highlight.py @@ -0,0 +1,27 @@ +from qtpy.QtWidgets import QApplication, QTextEdit + +from superqt.utils import CodeSyntaxHighlight + +app = QApplication([]) + +text_area = QTextEdit() +# (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(): + parser = ArgumentParser() + parser.add_argument("name", help="Your name") + args = parser.parse_args() + print(f"Hello {args.name}") + + +if __name__ == "__main__": + main() +""" +) +text_area.resize(400, 200) +text_area.show() + +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..997296e6 --- /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([]) + +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..6faa954f --- /dev/null +++ b/docs/examples/fonticon_animation.py @@ -0,0 +1,22 @@ +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 + +app = QApplication([]) + +window = QWidget() +layout = QHBoxLayout(window) +color = window.palette().color(QPalette.ColorRole.ButtonText).name() # (dark themes) + +spinning = QPushButton("spin") +spinning.setIcon(icon(FA5S.sync, color=color, animation=spin(spinning))) +layout.addWidget(spinning) + +pulsing = QPushButton("pulse") +pulsing.setIcon(icon(FA5S.spinner, color=color, animation=pulse(pulsing))) +layout.addWidget(pulsing) + +window.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/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/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..9aa5c39a --- /dev/null +++ b/docs/examples/qcolormap.py @@ -0,0 +1,19 @@ +from cmap import Colormap +from qtpy.QtWidgets import QApplication + +from superqt import QColormapComboBox + +app = QApplication([]) + +# (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"]) +# 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/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/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..16943873 --- /dev/null +++ b/docs/examples/qelidinglabel.py @@ -0,0 +1,14 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QElidingLabel + +app = QApplication([]) + +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." +) +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/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..273bd7a4 --- /dev/null +++ b/docs/examples/qlargeintspinbox.py @@ -0,0 +1,12 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QLargeIntSpinBox + +app = QApplication([]) + +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/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..46515d07 --- /dev/null +++ b/docs/examples/qsearchablelistwidget.py @@ -0,0 +1,11 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QSearchableListWidget + +app = QApplication([]) + +widget = QSearchableListWidget() +widget.addItems(["foo", "bar", "baz", "foobar", "foobaz", "barbaz"]) +widget.show() + +app.exec() diff --git a/docs/examples/qsearchabletreewidget.py b/docs/examples/qsearchabletreewidget.py new file mode 100644 index 00000000..7a15026c --- /dev/null +++ b/docs/examples/qsearchabletreewidget.py @@ -0,0 +1,22 @@ +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.tree.expandAll() +tree.show() + +app.exec() diff --git a/docs/examples/qtoggleswitch.py b/docs/examples/qtoggleswitch.py new file mode 100644 index 00000000..0e47b9ff --- /dev/null +++ b/docs/examples/qtoggleswitch.py @@ -0,0 +1,11 @@ +from qtpy.QtWidgets import QApplication + +from superqt import QToggleSwitch + +app = QApplication([]) + +switch = QToggleSwitch("Notifications") +switch.toggled.connect(print) +switch.show() + +app.exec() diff --git a/docs/examples/showcase.py b/docs/examples/showcase.py new file mode 100644 index 00000000..60f3e399 --- /dev/null +++ b/docs/examples/showcase.py @@ -0,0 +1,39 @@ +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) +form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) + +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/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 0fd1edc0..9f4e444f 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1,26 +1,35 @@ # 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 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/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/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 96573d72..cef65be8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,29 +1,102 @@ -# superqt +--- +hide: + - navigation + - toc +--- -## ![tiny](https://user-images.githubusercontent.com/1609449/120636353-8c3f3800-c43b-11eb-8732-a14dec578897.png) "missing" widgets and components for PyQt/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. +# ![](images/logo.svg#only-light){ .sq-logo }![](images/logo-dark.svg#only-dark){ .sq-logo } superqt -Components are tested on: +

"Missing" widgets and components for PyQt and PySide.

-- macOS, Windows, & Linux -- Python 3.11 and above -- PyQt5 (5.11 and above) & PyQt6 -- PySide6 +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 } + +
+ +{{ show_widget("showcase") }} + +
## Installation -```bash -pip install superqt -``` +=== "pip" + + ```bash + pip install superqt + ``` + +=== "uv" + + ```bash + uv add superqt + ``` + +=== "conda" + + ```bash + conda install -c conda-forge superqt + ``` + +superqt doesn't install a Qt binding. If your environment doesn't have one yet, +install one with an extra: ```bash -conda install -c conda-forge superqt +pip install "superqt[pyqt6]" # or [pyqt5], or [pyside6] ``` -## Usage +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/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 + + + +[All widgets](widgets/index.md){ .md-button } + +## Utilities + +The utilities 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. + + -See the [Widgets](./widgets/index.md) and [Utilities](./utilities/index.md) pages for features offered by superqt. +[All utilities](utilities/index.md){ .md-button } diff --git a/docs/javascripts/cards.js b/docs/javascripts/cards.js new file mode 100644 index 00000000..08866b7e --- /dev/null +++ b/docs/javascripts/cards.js @@ -0,0 +1,13 @@ +// Gallery cards: restart a card's animation from its first frame whenever the +// mouse enters the card. (An animated image keeps playing while it's hidden, so +// otherwise it would pick up wherever it happened to be.) The listener is on the +// document, so that it keeps working across instant navigation. +document.addEventListener("mouseover", (event) => { + const card = event.target.closest?.(".sq-card"); + if (!card || card.contains(event.relatedTarget)) return; + for (const img of card.querySelectorAll(".sq-card__anim")) { + const src = img.getAttribute("src"); + img.setAttribute("src", ""); + img.setAttribute("src", src); + } +}); diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css new file mode 100644 index 00000000..39f4b82d --- /dev/null +++ b/docs/stylesheets/extra.css @@ -0,0 +1,233 @@ +/* --------------------------------------------------------------------------- + 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; +} + +/* cards of a fixed width, in centered rows (so a short last row is centered) */ +.md-typeset .sq-gallery--center { + display: flex; + flex-wrap: wrap; + justify-content: center; +} + +.md-typeset .sq-gallery--center .sq-card { + flex: 0 0 100%; +} + +@media screen and (min-width: 45em) { + .md-typeset .sq-gallery--center .sq-card { + flex-basis: calc((100% - 0.8rem) / 2); + } +} + +@media screen and (min-width: 60em) { + .md-typeset .sq-gallery--center .sq-card { + flex-basis: calc((100% - 1.6rem) / 3); + } +} + +.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-thumb-light, var(--sq-figure-bg)); + border-bottom: 1px solid var(--sq-figure-border); +} + +[data-md-color-scheme="slate"] .md-typeset .sq-card__thumb { + background: var(--sq-thumb-dark, var(--sq-figure-bg)); +} + +.md-typeset .sq-card__thumb img { + max-width: 100%; + max-height: 100%; + height: auto; + object-fit: contain; +} + +/* a card with an animation plays it, instead of its still, while hovered */ +.md-typeset .sq-card__anim { + display: none; +} + +@media (hover: hover) and (prefers-reduced-motion: no-preference) { + .md-typeset .sq-card:hover .sq-card__still { + display: none; + } + + [data-md-color-scheme="default"] .md-typeset .sq-card:hover .sq-card__anim[src$="#only-light"], + [data-md-color-scheme="slate"] .md-typeset .sq-card:hover .sq-card__anim[src$="#only-dark"] { + display: inline; + } +} + +.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 h1 .sq-logo { + height: 2.2em; + margin-right: 0.3em; + vertical-align: -0.72em; +} + +.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/cmap.md b/docs/utilities/cmap.md index 06b571dd..e3af4ba5 100644 --- a/docs/utilities/cmap.md +++ b/docs/utilities/cmap.md @@ -1,12 +1,12 @@ # 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), +[`CmapCatalogComboBox`](../widgets/colormap_catalog.md), and +[`QColormapLineEdit`](../widgets/qcolormaplineedit.md)), for drawing +[cmap](https://cmap-docs.readthedocs.io/) colormaps elsewhere. They need the +`cmap` extra (`pip install "superqt[cmap]"`). ::: superqt.cmap.draw_colormap -::: superqt.cmap.QColormapLineEdit - ::: superqt.cmap.QColormapItemDelegate diff --git a/docs/utilities/code_syntax_highlight.md b/docs/utilities/code_syntax_highlight.md index 225a3eba..edaaf12f 100644 --- a/docs/utilities/code_syntax_highlight.md +++ b/docs/utilities/code_syntax_highlight.md @@ -1,52 +1,20 @@ # 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 -```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/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 deleted file mode 100644 index 8652f9e7..00000000 --- a/docs/utilities/fonticon.md +++ /dev/null @@ -1,124 +0,0 @@ -# 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/). - -## 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() - -app.exec() -``` - -{{ show_widget(225) }} - -## 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 - -Browse available icons at - -```bash -pip install fonticon-fontawesome6 -``` - -### Font Awesome 5 - -Browse available icons at - -```bash -pip install fonticon-fontawesome5 -``` - -### Material Design Icons 7 - -Browse available icons at - -```bash -pip install fonticon-materialdesignicons7 -``` - -### Material Design Icons 6 - -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 -``` - -### See also - -- -- -- - -`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: - -- -- -- - -## API - -::: superqt.fonticon.icon -options: -heading_level: 3 - -::: superqt.fonticon.setTextIcon -options: -heading_level: 3 - -::: superqt.fonticon.font -options: -heading_level: 3 - -::: superqt.fonticon.IconOpts -options: -heading_level: 3 - -::: superqt.fonticon.addFont -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 - -::: superqt.fonticon.pulse -options: -heading_level: 3 - -::: superqt.fonticon.spin -options: -heading_level: 3 diff --git a/docs/utilities/iconify.md b/docs/utilities/iconify.md deleted file mode 100644 index 1b9ae29c..00000000 --- a/docs/utilities/iconify.md +++ /dev/null @@ -1,36 +0,0 @@ -# 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) - -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")`. - -## Basic Example - -```python -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() -``` - -{{ show_widget(225) }} - -::: superqt.QIconifyIcon - options: - heading_level: 3 diff --git a/docs/utilities/icons/fonticon.md b/docs/utilities/icons/fonticon.md new file mode 100644 index 00000000..9617a2d4 --- /dev/null +++ b/docs/utilities/icons/fonticon.md @@ -0,0 +1,169 @@ +# Font icons + +`superqt.fonticon` creates `QIcon`s from the characters (glyphs) of icon fonts, +such as [Font Awesome](https://fontawesome.com/) or +[Material Design Icons](https://pictogrammers.com/library/mdi/). Icon fonts are +installed as plugins: superqt doesn't come with any. + +Compared with [`QIconifyIcon`](iconify.md), font icons don't need network +access, can be animated, and can be the text of a label or button (see the +[comparison](index.md#comparison)). + +## Installing a font + +These icon fonts are available as plugins, and as extras of superqt: + +| 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/)) | + +Other fonts are available as separate packages: + +- [fonticon-bootstrapicons](https://github.com/tlambert03/fonticon-bootstrapicons) +- [fonticon-linearicons](https://github.com/tlambert03/fonticon-linearicons) +- [fonticon-feather](https://github.com/tlambert03/fonticon-feather) + +[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). + +## Basic example + +{{ show_widget() }} + +```python +--8<-- +examples/fonticon.py +--8<-- +``` + +Glyphs are named by keys in the form `"prefix.name"`, such as `"fa5s.smile"`, +or by the constants of the classes that the plugins provide, such as +`FA5S.smile`, which IDEs autocomplete (and check for typos). + +## Colors and states + +`icon` takes the color, scale, opacity, and transform of the glyph. Without a +color, glyphs are black, whatever the widget's palette: for a dark theme, pass a +color (for example, one from the palette). + +`states` gives other options (including another glyph) for other states and +modes of the icon. Its keys are a state (`"on"`, `"off"`), a mode (`"normal"`, +`"active"`, `"selected"`, `"disabled"`), or both (as in `"on_disabled"`). For +example, a red heart when a checkable button is checked: + +```python +button.setCheckable(True) +button.setIcon( + icon( + FA5S.smile, + color="gray", + states={"on": {"glyph_key": FA5S.heart, "color": "red"}}, + ) +) +``` + +In modes other than normal (such as disabled), a glyph without a color for that +mode is adjusted by the style, like any other icon (for example, grayed out when +disabled). + +## Animations + +The `animation` argument of `icon()` takes an +[`Animation`](#superqt.fonticon.Animation), such as `spin` or `pulse`, created +with the widget that shows the icon: + +{{ show_widget("fonticon_animation") }} + +```python +--8<-- +examples/fonticon_animation.py +--8<-- +``` + +## Glyphs as text + +`setTextIcon` makes a glyph the text of a widget, such as a label or a button, +by setting its text to the glyph and its font to the icon font. The glyph is then +drawn as text, in the widget's text color, so it follows the palette and style +sheets: + +```python +label = QLabel() +setTextIcon(label, FA5S.smile, size=32) +label.setStyleSheet("color: orange") +``` + +`font` returns the `QFont` of an icon font (by its prefix, such as `"fa5s"`), for +drawing glyphs yourself. + +## Writing a plugin + +Font packages register themselves with the `"superqt.fonticon"` +[entry point](https://packaging.python.org/en/latest/specifications/entry-points/) +(`superqt.fonticon.ENTRY_POINT`), and define their glyphs with an +[`IconFont`](#superqt.fonticon.IconFont) subclass (whose metaclass, +`IconFontMeta`, turns its attributes into glyph keys). +[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 + +### Icons + +::: superqt.fonticon.icon + options: + heading_level: 4 + +::: superqt.fonticon.IconOpts + options: + heading_level: 4 + +### Text + +::: superqt.fonticon.setTextIcon + options: + heading_level: 4 + +::: superqt.fonticon.font + options: + heading_level: 4 + +### Fonts + +::: superqt.fonticon.addFont + options: + heading_level: 4 + +::: superqt.fonticon.IconFont + options: + heading_level: 4 + +::: superqt.fonticon.IconFontMeta + options: + heading_level: 4 + +::: superqt.fonticon.ENTRY_POINT + options: + heading_level: 4 + show_if_no_docstring: true + +### Animations + +::: superqt.fonticon.Animation + options: + heading_level: 4 + +::: superqt.fonticon.spin + options: + heading_level: 4 + +::: superqt.fonticon.pulse + options: + heading_level: 4 diff --git a/docs/utilities/icons/iconify.md b/docs/utilities/icons/iconify.md new file mode 100644 index 00000000..1c6f3dce --- /dev/null +++ b/docs/utilities/icons/iconify.md @@ -0,0 +1,112 @@ +# QIconifyIcon + +A `QIcon` with one of the SVG icons of [Iconify](https://iconify.design/): over +450,000 icons, from more than 260 open source icon sets. Find an icon at +, and create it with its key, in the form +`"prefix:name"`: `QIconifyIcon("bi:bell")`. (For a comparison with font icons, +see [Icons](index.md#comparison).) + +!!! note "Requires pyconify" + + Icons are downloaded with [pyconify](https://github.com/pyapp-kit/pyconify), + which you can install with the `iconify` extra: + + ```bash + pip install "superqt[iconify]" + ``` + +## Example + +{{ show_widget() }} + +```python +--8<-- +examples/iconify.py +--8<-- +``` + +## Colors, rotation, and states + +Single-color icons can be colored, and any icon can be flipped or rotated: + +```python +--8<-- +examples/iconify_color.py:icon +--8<-- +``` + +{{ show_widget("iconify_color") }} + +Without a `color`, single-color icons are black, whatever the widget's palette. +For a dark theme, pass a color, for example one from the palette: + +```python +--8<-- +examples/iconify_palette.py:icon +--8<-- +``` + +{{ show_widget("iconify_palette") }} + +`addKey` adds icons for other states and modes of the same `QIcon`. For +example, a different icon when a checkable button is checked: + +```python +--8<-- +examples/iconify_states.py:icon +--8<-- +``` + +{{ show_widget("iconify_states") }} + +## How icons are fetched + +The first time an icon is used, pyconify downloads it from the Iconify API +(`api.iconify.design`), and saves it in a cache on disk, where later sessions +find it. + +- The download happens when the `QIconifyIcon` is created, in the thread that + creates it, which waits for it (with a timeout of 2 seconds). +- The first icon of each session also asks the API when the icon sets last + changed, so that cached icons that are out of date are downloaded again. +- Without network access, cached icons still load. An icon that isn't cached + causes a warning, and is replaced by a question mark icon. +- `pyconify.get_cache_directory()` returns the location of the cache. To use + another directory, set the `PYCONIFY_CACHE` environment variable to it (or to + `0`, to turn the cache off) before `superqt.iconify` (or pyconify) is imported. + +## Using icons offline, or in an app + +To make sure that an app's icons are available without network access, ship +them in a cache directory: + +1. Fill a directory with the icons: create each of them once (for example, by + running the app), with `PYCONIFY_CACHE` set to that directory. +2. Ship the directory with the app, and set `PYCONIFY_CACHE` to it before + importing `superqt.iconify`: + + ```python + import os + from pathlib import Path + + os.environ["PYCONIFY_CACHE"] = str(Path(__file__).parent / "icon_cache") + + from superqt import QIconifyIcon + ``` + +The icons are then loaded from the directory. With network access, an icon whose +set has changed since is downloaded again, into the same directory (so it should +be writable). + +## Licenses + +Each icon set has its own license. Most are permissive (such as MIT or Apache +2.0), but many require attribution (CC BY 4.0), and a few are GPL. The license of +a set is shown on its page at , and returned by +`pyconify.collections()`. + +## API + +::: superqt.QIconifyIcon + options: + heading_level: 3 diff --git a/docs/utilities/icons/index.md b/docs/utilities/icons/index.md new file mode 100644 index 00000000..8190602b --- /dev/null +++ b/docs/utilities/icons/index.md @@ -0,0 +1,41 @@ +--- +hide: + - toc +--- + +# Icons + +superqt can create a `QIcon` from an icon library in two ways: + +- [`QIconifyIcon`](iconify.md) uses the SVG icons of [Iconify](https://iconify.design/): + over 450,000 icons, from more than 260 icon sets (including Bootstrap Icons, + Font Awesome, and Material Design Icons). It's the usual choice: any icon is + available without choosing an icon set in advance. +- [Font icons](fonticon.md) (`superqt.fonticon`) draw the characters of icon + fonts that you install as plugins. They work without network access, can be + animated, and can be the text of a label or button. + + + +## Comparison + +Most of the differences follow from one detail: `QIconifyIcon` draws SVG images +that are downloaded (and cached) the first time they're used, while +`superqt.fonticon` draws the characters of a font file that's installed in +advance, as a plugin. + +| | [`QIconifyIcon`](iconify.md) | [`superqt.fonticon`](fonticon.md) | +| --- | --- | --- | +| **What it draws** | An SVG image, drawn by Qt's SVG support | A character of an icon font, drawn as text | +| In text | No: only where an icon or image goes | Yes: [`setTextIcon`](fonticon.md#glyphs-as-text) makes a glyph the text of a label or button (in its text color), and `font()` gives the font | +| Colors | One color with `color=`, or the icon's own colors (e.g. emoji) | One color: the glyph's | +| Animation | No | `spin`, `pulse`, or a custom `Animation` | +| **Icons available** | Over 450,000 icons, from 260+ icon sets | Only fonts installed as plugins (none by default): Font Awesome 5 and 6, Material Design Icons 6 and 7, and a few others | +| Install | `superqt[iconify]` (pyconify, requests) | One package per font (e.g. `superqt[font-fa6]`), which contains the font | +| Network | Each icon is [downloaded on first use](iconify.md#how-icons-are-fetched), then cached on disk; offline and uncached, you get a "?" placeholder | None | +| **Naming icons** | `"prefix:name"` strings | Constants with IDE autocompletion and typo checking, such as `FA5S.smile`, or `"fa5s.smile"` strings | +| Per state/mode | `addKey(..., mode=, state=)` | `states={...}` | +| Bundling with an app | [Ship a pre-filled pyconify cache](iconify.md#using-icons-offline-or-in-an-app) | The font is in the plugin package | 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..71af8149 100644 --- a/docs/utilities/index.md +++ b/docs/utilities/index.md @@ -1,38 +1,63 @@ # 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 + +superqt has two ways to create icons from icon libraries: see +[Icons](icons/index.md) for how they compare. + +| Object | Description | +| --- | --- | +| [`QIconifyIcon`](icons/iconify.md) | A `QIcon` with any of the SVG icons from [Iconify](https://iconify.design/). | +| [`icon`](icons/fonticon.md#superqt.fonticon.icon) | Create a `QIcon` from a glyph in an icon font. | +| [`setTextIcon`](icons/fonticon.md#superqt.fonticon.setTextIcon) | Show a glyph from an icon font as the text of a widget. | +| [`font`](icons/fonticon.md#superqt.fonticon.font) | Create the `QFont` of an icon font. | +| [`addFont`](icons/fonticon.md#superqt.fonticon.addFont) | Add an OTF or TTF font file to the icon font registry. | +| [`IconFont`](icons/fonticon.md#superqt.fonticon.IconFont) | Base class for defining the glyphs of an icon font. | +| [`IconFontMeta`](icons/fonticon.md#superqt.fonticon.IconFontMeta) | Metaclass of `IconFont`, which turns its attributes into glyph keys. | +| [`ENTRY_POINT`](icons/fonticon.md#superqt.fonticon.ENTRY_POINT) | The entry point group that font plugins register with. | +| [`IconOpts`](icons/fonticon.md#superqt.fonticon.IconOpts) | Options for drawing an icon in a given state (color, scale, and so on). | +| [`Animation`](icons/fonticon.md#superqt.fonticon.Animation), [`spin`](icons/fonticon.md#superqt.fonticon.spin), [`pulse`](icons/fonticon.md#superqt.fonticon.pulse) | Animations for font icons. | + +## 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#superqt.utils.ensure_main_thread) | Decorator that makes a function run in the main thread. | +| [`ensure_object_thread`](thread_decorators.md#superqt.utils.ensure_object_thread) | 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`. | +| [`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. | +| [`QStyleOptionToggleSwitch`](../widgets/qtoggleswitch.md#superqt.switch.QStyleOptionToggleSwitch) | The style option that `QToggleSwitch` draws itself with (for subclasses). | +| [`MONTEREY_SLIDER_STYLES_FIX`](../faq.md#superqt.sliders.MONTEREY_SLIDER_STYLES_FIX) | A style sheet that works around a slider bug of Qt 5 on macOS 12+. | 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..349d8b87 100644 --- a/docs/utilities/thread_decorators.md +++ b/docs/utilities/thread_decorators.md @@ -1,99 +1,105 @@ # 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. +## Waiting for the result -These decorators should not be used as replacement of Qt Signals but rather to -interact with Qt objects from non Qt code. +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`. -## Synchronous mode +!!! warning -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. - -!!! 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 ``` + +## API + +::: superqt.utils.ensure_main_thread + options: + heading_level: 3 + +::: superqt.utils.ensure_object_thread + options: + heading_level: 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..2172642f 100644 --- a/docs/utilities/throttling.md +++ b/docs/utilities/throttling.md @@ -1,46 +1,70 @@ -# 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. -- -- +Below, a slider's `valueChanged` signal is connected to a function directly, and +to the same function decorated with `qthrottled` and with `qdebounced`. Each +tick is a call, and the value is what the last call received: -::: superqt.utils.qdebounced - options: - show_source: false - docstring_style: numpy - show_root_toc_entry: True - show_root_heading: True +{{ show_widget("throttling") }} + +??? example "The code for this demo" + + ```python + --8<-- + examples/throttling.py + --8<-- + ``` + +For more background, see +[Debouncing and throttling explained](https://css-tricks.com/debouncing-throttling-explained-examples/). + +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 48da710b..de05e939 100644 --- a/docs/widgets/colormap_catalog.md +++ b/docs/widgets/colormap_catalog.md @@ -1,35 +1,31 @@ # 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. -```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..8c6b3423 100644 --- a/docs/widgets/index.md +++ b/docs/widgets/index.md @@ -1,37 +1,63 @@ +--- +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. | +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 9e52fc25..26bd0941 100644 --- a/docs/widgets/qcollapsible.md +++ b/docs/widgets/qcollapsible.md @@ -1,24 +1,22 @@ # 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`. -```python -from qtpy.QtWidgets import QApplication, QLabel, QPushButton - -from superqt import QCollapsible - -app = QApplication([]) +- `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. -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}")) +{{ show_widget() }} -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..151b4aa2 100644 --- a/docs/widgets/qcolorcombobox.md +++ b/docs/widgets/qcolorcombobox.md @@ -1,27 +1,23 @@ # 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. -```python -from qtpy.QtWidgets import QApplication - -from superqt import QColorComboBox - -app = QApplication([]) - -colors = QColorComboBox() -colors.addColors(["red", "green", "blue"]) +- 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 an "Add Color" item that opens a QColorDialog when clicked -colors.setUserColorsAllowed(True) +{{ show_widget() }} -# 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..c94f0677 100644 --- a/docs/widgets/qcolormap.md +++ b/docs/widgets/qcolormap.md @@ -1,63 +1,53 @@ # 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 -```python -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")) +{{ show_widget() }} -cmap_combo.show() -app.exec() +```python +--8<-- +examples/qcolormap.py +--8<-- ``` -{{ show_widget(200) }} - -### 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: +(The line edit is a [`QColormapLineEdit`](qcolormaplineedit.md).) + +To make the colormaps in the list fill a third of their width: ```python from superqt.cmap import QColormapItemDelegate diff --git a/docs/widgets/qcolormaplineedit.md b/docs/widgets/qcolormaplineedit.md new file mode 100644 index 00000000..1c46d4ce --- /dev/null +++ b/docs/widgets/qcolormaplineedit.md @@ -0,0 +1,33 @@ +# QColormapLineEdit + +A [`QLineEdit`](https://doc.qt.io/qt-6/qlineedit.html) that shows the colormap +named by its text, as you type: a swatch next to the name, or, if +`fractional_colormap_width` is more than 0.75, behind it. When the text isn't the +name of a colormap in the [cmap catalog](https://cmap-docs.readthedocs.io/en/latest/catalog/), +it shows a fallback colormap (gray, by default), and a question mark icon next to +the name (unless the swatch is behind it). It's the +line edit of [`QColormapComboBox`](qcolormap.md) and +[`CmapCatalogComboBox`](colormap_catalog.md). + +!!! note "Requires cmap" + + Colormaps come from the [cmap](https://cmap-docs.readthedocs.io/) library, + which you can install with the `cmap` extra: + + ```bash + pip install "superqt[cmap]" + ``` + +{{ show_widget() }} + +```python +--8<-- +examples/qcolormaplineedit.py +--8<-- +``` + +With `allow_invalid=False`, text that isn't a colormap is replaced when editing +finishes: by the first completion of the line edit's completer, if it has one, +or else by the last valid colormap. + +{{ show_members('superqt.cmap.QColormapLineEdit') }} diff --git a/docs/widgets/qdoublerangeslider.md b/docs/widgets/qdoublerangeslider.md index 128ee67c..92a6de95 100644 --- a/docs/widgets/qdoublerangeslider.md +++ b/docs/widgets/qdoublerangeslider.md @@ -1,23 +1,14 @@ # 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. -```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..ec58cc46 100644 --- a/docs/widgets/qdoubleslider.md +++ b/docs/widgets/qdoubleslider.md @@ -1,23 +1,15 @@ # 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`). -```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..93435490 100644 --- a/docs/widgets/qelidinglabel.md +++ b/docs/widgets/qelidinglabel.md @@ -1,26 +1,22 @@ # 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. -```python -from qtpy.QtWidgets import QApplication - -from superqt import QElidingLabel +- `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. -app = QApplication([]) +For a line edit that does the same, see [`QElidingLineEdit`](qelidinglineedit.md). -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() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qelidinglabel.py +--8<-- ``` -{{ show_widget(300) }} - {{ show_members('superqt.QElidingLabel') }} 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 28c20779..28754575 100644 --- a/docs/widgets/qenumcombobox.md +++ b/docs/widgets/qenumcombobox.md @@ -1,42 +1,26 @@ # 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` - -```python -from enum import Enum - -from qtpy.QtWidgets import QApplication -from superqt import QEnumComboBox - - -class SampleEnum(Enum): - first = 1 - second = 2 - third = 3 +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. -app = QApplication([]) +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`. -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 +The `Enum` can also be passed to the constructor: ```python # option A: @@ -48,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 @@ -62,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 74e5f88c..2d52d076 100644 --- a/docs/widgets/qflowlayout.md +++ b/docs/widgets/qflowlayout.md @@ -1,29 +1,15 @@ # 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. -```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..c9b0ed5a 100644 --- a/docs/widgets/qlabeleddoublerangeslider.md +++ b/docs/widgets/qlabeleddoublerangeslider.md @@ -1,23 +1,15 @@ # 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. -```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..a68a2ad9 100644 --- a/docs/widgets/qlabeleddoubleslider.md +++ b/docs/widgets/qlabeleddoubleslider.md @@ -1,24 +1,16 @@ # 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() }} ```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..cfa4d898 100644 --- a/docs/widgets/qlabeledrangeslider.md +++ b/docs/widgets/qlabeledrangeslider.md @@ -1,29 +1,31 @@ # QLabeledRangeSlider -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() - -app.exec_() -``` +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() }} -{{ show_members('superqt.QLabeledRangeSlider') }} +```python +--8<-- +examples/qlabeledrangeslider.py +--8<-- +``` ----- +!!! 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 66cb2de3..fef37e20 100644 --- a/docs/widgets/qlabeledslider.md +++ b/docs/widgets/qlabeledslider.md @@ -1,22 +1,20 @@ # 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. -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QLabeledSlider +`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`). -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..54b98302 100644 --- a/docs/widgets/qlargeintspinbox.md +++ b/docs/widgets/qlargeintspinbox.md @@ -1,23 +1,19 @@ # 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`. -```python -from qtpy.QtCore import Qt -from qtpy.QtWidgets import QApplication - -from superqt import QLargeIntSpinBox - -app = QApplication([]) +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. -slider = QLargeIntSpinBox() -slider.setRange(0, 4.53e8) -slider.setValue(4.53e8) -slider.show() +{{ show_widget() }} -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..d53b150a 100644 --- a/docs/widgets/qquantity.md +++ b/docs/widgets/qquantity.md @@ -1,39 +1,30 @@ # 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: + ```bash + pip install "superqt[quantity]" ``` - pip install pint - ``` - - or - ``` - pip install superqt[quantity] - ``` +{{ show_widget() }} ```python -from qtpy.QtWidgets import QApplication - -from superqt import QQuantity - -app = QApplication([]) -w = QQuantity("1m") -w.show() - -app.exec() +--8<-- +examples/qquantity.py +--8<-- ``` -!!! note - - `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. +!!! warning "Only one dimension" -{{ show_widget(150) }} + `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 0babaa95..ee6ffd81 100644 --- a/docs/widgets/qrangeslider.md +++ b/docs/widgets/qrangeslider.md @@ -1,50 +1,43 @@ # 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. -```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` 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)): -- `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])`) +- 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). -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.) +These methods, in addition to those of `QSlider`, control the bar between the +handles: -These options are in addition to the Qt QSlider API, and control the behavior of the bar between handles. +| 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. | -| 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. | +### Native styles -### Screenshots +`QRangeSlider` and `QSlider`, unstyled and with the same style sheet, on each +platform: -??? title "code that generates the images below" +??? example "Code for these screenshots" ```python import os @@ -177,52 +170,36 @@ 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 -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 63fa3254..352e7dd0 100644 --- a/docs/widgets/qsearchablecombobox.md +++ b/docs/widgets/qsearchablecombobox.md @@ -1,25 +1,16 @@ # 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() }} ```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..f2edef2b 100644 --- a/docs/widgets/qsearchablelistwidget.md +++ b/docs/widgets/qsearchablelistwidget.md @@ -1,28 +1,21 @@ # 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. -```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..b38fdd32 100644 --- a/docs/widgets/qsearchabletreewidget.md +++ b/docs/widgets/qsearchabletreewidget.md @@ -1,37 +1,23 @@ # 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. -```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() +{{ show_widget() }} -app.exec_() +```python +--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..1b7e4798 100644 --- a/docs/widgets/qtoggleswitch.md +++ b/docs/widgets/qtoggleswitch.md @@ -1,24 +1,28 @@ # 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. -```python -from qtpy.QtWidgets import QApplication - -from superqt import QToggleSwitch - -app = QApplication([]) +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`, +which are given a `superqt.switch.QStyleOptionToggleSwitch` with the colors and +sizes to use. -switch = QToggleSwitch() -switch.show() +{{ show_widget() }} -app.exec_() +```python +--8<-- +examples/qtoggleswitch.py +--8<-- ``` -{{ show_widget(80) }} - {{ show_members('superqt.QToggleSwitch') }} + +::: superqt.switch.QStyleOptionToggleSwitch + options: + heading_level: 3 + show_if_no_docstring: true diff --git a/examples/icon_explorer.py b/examples/icon_explorer.py index 8f2c80fc..38368cda 100644 --- a/examples/icon_explorer.py +++ b/examples/icon_explorer.py @@ -5,7 +5,10 @@ P = loaded(load_all=True) if not P: - print("you have no font packs loaded!") + raise ModuleNotFoundError( + "This example requires a font pack, such as fontawesome:\n\n" + "pip install fonticon-fontawesome6" + ) class GlyphDelegate(QtWidgets.QItemDelegate): 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/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/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", diff --git a/src/superqt/iconify/__init__.py b/src/superqt/iconify/__init__.py index c35fc9fd..30c25f32 100644 --- a/src/superqt/iconify/__init__.py +++ b/src/superqt/iconify/__init__.py @@ -28,8 +28,8 @@ class QIconifyIcon(QIcon): """QIcon backed by an iconify icon. - Iconify includes 150,000+ icons from most major icon sets including Bootstrap, - FontAwesome, Material Design, and many more. + Iconify includes over 450,000 icons from 260+ icon sets, including Bootstrap, + Font Awesome, Material Design, and many more. Search available icons at https://icon-sets.iconify.design Once you find one you like, use the key in the format `"prefix:name"` to create an 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/tests/test_docs.py b/tests/test_docs.py new file mode 100644 index 00000000..9dea1bdd --- /dev/null +++ b/tests/test_docs.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import importlib +import pkgutil +import re +from contextlib import suppress +from pathlib import Path +from typing import Any + +import pytest + +import superqt + +DOCS = Path(__file__).parent.parent / "docs" +MODULES = ["superqt"] + [ + f"superqt.{m.name}" + for m in pkgutil.iter_modules(superqt.__path__) + if not m.name.startswith("_") and m.name != "qtcompat" # (deprecated) +] +# objects that get an mkdocstrings section (and so an anchor, and an inventory entry) +DIRECTIVE = re.compile(r"^::: *([\w.]+)|show_members\(['\"]([\w.]+)['\"]\)", re.M) + + +def _resolve(path: str) -> Any: + parts = path.split(".") + for i in range(len(parts), 0, -1): + with suppress(ModuleNotFoundError): + obj = importlib.import_module(".".join(parts[:i])) + for part in parts[i:]: + obj = getattr(obj, part) + return obj + raise ImportError(path) + + +def _documented() -> list[Any]: + objects = [] + for md in DOCS.rglob("*.md"): + for path in filter(None, sum(DIRECTIVE.findall(md.read_text()), ())): + with suppress(ImportError): # (optional dependencies) + objects.append(_resolve(path)) + return objects + + +@pytest.mark.skipif(not DOCS.exists(), reason="docs/ not available") +@pytest.mark.parametrize("module", MODULES) +def test_public_names_have_api_docs(module: str) -> None: + mod = pytest.importorskip(module) + documented = _documented() + missing = [ + name + for name in mod.__all__ + if not any(getattr(mod, name) is obj for obj in documented) + ] + assert not missing, f"no `:::` or `show_members` in docs/ for {module}: {missing}" + + # ... and is listed: in the widget gallery or the utilities index + pages = ("widgets/index.md", "utilities/index.md") + lists = "".join((DOCS / page).read_text() for page in pages) + unlisted = [name for name in mod.__all__ if not re.search(rf"\b{name}\b", lists)] + assert not unlisted, f"not listed in the widget or utilities index: {unlisted}" diff --git a/tests/test_examples.py b/tests/test_examples.py new file mode 100644 index 00000000..d6f2dbfe --- /dev/null +++ b/tests/test_examples.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pytest +from qtpy import QtWidgets +from qtpy.QtWidgets import QApplication + +from superqt.fonticon._plugins import FontIconManager +from superqt.fonticon._qfont_icon import QFontIconStore + +if TYPE_CHECKING: + from collections.abc import Iterator + + from pytestqt.qtbot import QtBot + +ROOT = Path(__file__).parent.parent +EXAMPLES = sorted([*ROOT.glob("docs/examples/*.py"), *ROOT.glob("examples/*.py")]) + + +class _App: + """What an example gets for `QApplication([])`: the running app, whose `exec` + returns at once.""" + + 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 _AppClass(type): + def __call__(cls, *_: Any, **__: Any) -> _App: + return _App(QApplication.instance()) + + def __getattr__(cls, name: str) -> Any: # (static methods, enums, ...) + return getattr(QApplication, name) + + +class _QApplication(metaclass=_AppClass): + pass + + +@pytest.fixture(autouse=True) +def _unload_fonts(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + """Unload the font packs that examples load (other tests expect none).""" + monkeypatch.setattr(FontIconManager, "_LOADED", {}) + yield + QFontIconStore.clear() + + +@pytest.mark.parametrize( + "path", EXAMPLES, ids=[str(p.relative_to(ROOT)) for p in EXAMPLES] +) +def test_example( + path: Path, qapp: QApplication, qtbot: QtBot, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(QtWidgets, "QApplication", _QApplication) + before = set(QApplication.topLevelWidgets()) + code = compile(path.read_text(encoding="utf-8"), str(path), "exec") + namespace = {"__name__": "__main__", "__file__": str(path)} # (keeps widgets) + try: + exec(code, namespace) + except ModuleNotFoundError as e: + pytest.skip(f"needs {e.name or e}") + except SystemExit: + pass + finally: + # (hidden ones, like a completer's popup, are deleted with their owner) + shown = [ + w + for w in QApplication.topLevelWidgets() + if w not in before and w.isVisible() and w.parent() is None + ] + for window in shown: + qtbot.addWidget(window) # (closed and deleted after the test) + + # (the docs render each of their examples' window) + if path.parent.parent.name == "docs": + assert len(shown) == 1, f"shows {len(shown)} windows, not 1" + else: + assert shown, "shows no window" diff --git a/zensical.toml b/zensical.toml new file mode 100644 index 00000000..7d5f6829 --- /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" +copyright = "Copyright © 2021 - 2026 superqt contributors" + +extra_css = ["stylesheets/extra.css"] +extra_javascript = ["javascripts/cards.js"] + +exclude_docs = """ +_*.py +__pycache__/ +examples/ +_generated/manifest.json +""" + +nav = [ + { "Home" = "index.md" }, + { "Widgets" = [ + "widgets/index.md", + { "Sliders" = [ + "widgets/qrangeslider.md", + "widgets/qdoubleslider.md", + "widgets/qdoublerangeslider.md", + "widgets/qlabeledslider.md", + "widgets/qlabeleddoubleslider.md", + "widgets/qlabeledrangeslider.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/qelidinglineedit.md", + "widgets/qcolormaplineedit.md", + "widgets/qtoggleswitch.md", + ] }, + { "Containers and layouts" = [ + "widgets/qcollapsible.md", + "widgets/qflowlayout.md", + ] }, + ] }, + { "Utilities" = [ + "utilities/index.md", + { "Icons" = [ + "utilities/icons/index.md", + "utilities/icons/iconify.md", + "utilities/icons/fonticon.md", + ] }, + { "Threading" = [ + "utilities/threading.md", + "utilities/thread_decorators.md", + ] }, + { "Signals" = [ + "utilities/throttling.md", + "utilities/signal_utils.md", + ] }, + { "Messages and errors" = [ + "utilities/qmessagehandler.md", + "utilities/error_dialog_contexts.md", + ] }, + { "Miscellaneous" = [ + "utilities/code_syntax_highlight.md", + "utilities/cmap.md", + "utilities/images.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] +favicon = "images/favicon.svg" +features = [ + "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" + +[[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 = {} +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", "utilities/icons/index.md"] +targets.include = ["widgets/*", "utilities/*"] + +# ---------------------------------------------------------------------------- +# Plugins + +# pages that moved +[project.plugins.redirects.redirect_maps] +"utilities/fonticon.md" = "utilities/icons/fonticon.md" +"utilities/iconify.md" = "utilities/icons/iconify.md" + +[project.plugins.autorefs] +resolve_closest = true + +[project.plugins.macros] +module_name = "docs/_macros" +# (no includes: zensical watches the files in `include_dir`, so that pages are +# rebuilt with the screenshots' sizes, from `manifest.json`, when they change) +include_dir = "docs/_generated" +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