Metadata-Version: 2.4
Name: qthemer
Version: 0.2.1
Summary: Runtime dynamic PySide6 theme manager for custom apps.
Keywords: pyside6,qt,qt6,theme,dark-mode,qss,pyqtgraph,matplotlib
Author: Nicolás Vera Castillo
Author-email: Nicolás Vera Castillo <nicolas.vera@uc.cl>
License-Expression: MIT
License-File: LICENSE
License-File: src/qthemer/resources/icons/LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: X11 Applications :: Qt
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: User Interfaces
Classifier: Typing :: Typed
Requires-Dist: pydantic>=2.14.2
Requires-Dist: pyside6>=6.6.0,!=6.12.0 ; python_full_version < '3.12'
Requires-Dist: pyside6>=6.6.0 ; python_full_version >= '3.12'
Requires-Dist: matplotlib>=3.11.2 ; extra == 'matplotlib'
Requires-Dist: matplotlib>=3.11.2 ; extra == 'plots'
Requires-Dist: pyqtgraph>=0.14.0 ; extra == 'plots'
Requires-Dist: pyqtgraph>=0.14.0 ; extra == 'pyqtgraph'
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/tugatoconhelado/qthemer
Project-URL: Repository, https://github.com/tugatoconhelado/qthemer
Project-URL: Issues, https://github.com/tugatoconhelado/qthemer/issues
Project-URL: Changelog, https://github.com/tugatoconhelado/qthemer/blob/main/CHANGELOG.md
Provides-Extra: matplotlib
Provides-Extra: plots
Provides-Extra: pyqtgraph
Description-Content-Type: text/markdown

# qthemer

**Runtime dynamic theme manager for PySide6 applications.**

`qthemer` enables seamless, instantaneous theme switching in PySide6 applications without requiring application restarts or widget reconstruction. It combines native `QPalette` configuration, modern Qt Style Sheet (QSS) generation, and a dynamic vector SVG proxy style that recolors standard Qt icons on the fly.

| Dark (Catppuccin Mocha) | Light (Catppuccin Latte) |
| :---: | :---: |
| ![Dark Workbench](https://raw.githubusercontent.com/tugatoconhelado/qthemer/main/docs/assets/demo-dark.png) | ![Light Workbench](https://raw.githubusercontent.com/tugatoconhelado/qthemer/main/docs/assets/demo-light.png) |

![Live Plot Theming](https://raw.githubusercontent.com/tugatoconhelado/qthemer/main/docs/assets/plots-demo.png)

---

## Key Features

- ⚡ **Zero-Restart Runtime Switching**: Switch themes instantly across the entire application or target individual widgets and sub-trees in isolation.
- 🎨 **Tiered Styling Modes (`StyleMode`)**:
  - **`FULL`**: A complete, polished design system for modern desktop applications and workbenches.
  - **`MINIMAL`**: Styles workbench chrome (dock panels, tab bars, splitters, scrollbars, group boxes, headers) while preserving native widget metrics for buttons and text inputs.
  - **`PALETTE`**: Fast, stylesheet-free theming utilizing only native `QPalette` color roles and SVG vector icon recoloring.
- 📐 **UI Density Presets (`Density`)**: Switch between `COMPACT`, `NORMAL`, and `COMFORTABLE` spacing, padding, and control sizing at runtime.
- 🖼️ **Dynamic Vector SVG Proxy Style (`ThemedProxyStyle`)**: Replaces standard Qt pixmaps (message boxes, navigation chevrons, title bar controls, media buttons) with crisp vector SVG icons tinted to the active theme's tokens.
- 🌓 **Automatic OS Theme Synchronization**: Seamlessly responds to operating system dark and light mode shifts (`system` theme mode) via `QStyleHints`.
- 💾 **State Persistence**: Remembers user theme choices across sessions using `QSettings`.
- 🧩 **Semantic Color Tokens**: Strongly typed [Pydantic](https://docs.pydantic.dev/) models (`surface`, `text`, `accent`, `status`, `plot`) with automatic fallback resolution.
- 📦 **8 Built-in Themes**: Catppuccin Mocha, Catppuccin Latte, Dracula, Gruvbox Dark, Nord, One Dark, Solarized Light, and Tokyo Night.
- 🛠️ **Drop-in UI Helpers**:
  - `ThemeSelectorDialog`: Modal theme manager with live isolated widget preview, theme switcher, and custom TOML/JSON theme import.
  - `create_toggle_action`: Menu or toolbar action with auto-syncing sun/moon icons for dark/light toggling.
  - `create_dialog_action`: One-line action to launch the theme selector dialog.
- 📈 **Live Plot Theming**: Built-in, optional adapters for **`pyqtgraph`** and **`matplotlib`** with `manager.bind_plot(...)`, `rcParams` generation, and an extensible `PlotAdapter` protocol.

---

## Installation

`qthemer` requires **Python >= 3.11** and **PySide6 >= 6.6.0**.

Install from PyPI via `pip`:

```bash
pip install qthemer

# With optional plotting support:
pip install "qthemer[pyqtgraph]"
pip install "qthemer[matplotlib]"
pip install "qthemer[plots]"
```

Or using `uv`:

```bash
uv add qthemer
uv add qthemer --extra plots
```

---

## Quickstart

Here is a minimal, complete application featuring dynamic theme switching:

```python
import sys
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QPushButton,
    QVBoxLayout,
    QWidget,
)
from qthemer import ThemeManager, create_dialog_action, create_toggle_action


def main() -> None:
    app = QApplication(sys.argv)

    # 1. Initialize ThemeManager (automatically installs proxy style and themes app)
    manager = ThemeManager(initial_theme="catppuccin_mocha")

    # 2. Build your window
    window = QMainWindow()
    window.setWindowTitle("qthemer Quickstart")
    window.resize(600, 400)

    # 3. Add drop-in theme actions to menu
    view_menu = window.menuBar().addMenu("&View")
    view_menu.addAction(create_toggle_action(manager, parent=window))
    view_menu.addAction(create_dialog_action(manager, parent=window))

    # 4. Central content
    central = QWidget()
    layout = QVBoxLayout(central)

    btn_toggle = QPushButton("Toggle Dark / Light")
    btn_toggle.clicked.connect(manager.toggle_dark_light)
    layout.addWidget(btn_toggle)

    window.setCentralWidget(central)
    window.show()

    sys.exit(app.exec())


if __name__ == "__main__":
    main()
```

---

## Styling Architecture

Styling Qt applications is often fraught with trade-offs: pure `QPalette` cannot style dock panels or modern tab indicators, while heavy custom QSS often destroys native widget metrics (such as button padding and spinbox line-edit alignments).

`qthemer` addresses this with a coordinated three-layer architecture:

```
┌─────────────────────────────────────────────────────────┐
│                      ThemeManager                       │
└──────┬──────────────────────┬────────────────────┬──────┘
       │                      │                    │
       ▼                      ▼                    ▼
┌──────────────┐      ┌───────────────┐    ┌───────────────┐
│   QPalette   │      │ThemedProxyStyl│    │  QSS Builder  │
│  (All Roles) │      │  (Vector SVG) │    │ (StyleMode)   │
└──────────────┘      └───────────────┘    └───────────────┘
```

1. **`build_palette(tokens)`**: Sets up standard Qt color roles (`Window`, `WindowText`, `Base`, `AlternateBase`, `Button`, `Highlight`, `Link`, `PlaceholderText`, etc.) across `Active`, `Inactive`, and `Disabled` states.
2. **`ThemedProxyStyle`**: Extends Qt's `Fusion` style to intercept `standardIcon()` queries. Standard pixmaps (e.g., `SP_MessageBoxInformation`, `SP_ArrowRight`) are loaded from bundled SVGs, colored according to semantic tokens, and cached. It also polishes button tab focus policies and spinbox margins in `FULL` mode.
3. **`StyleSheetBuilder`**: Compiles stylesheet templates containing token variables (`$surface_window`, `$accent_primary`, `${icon:sun:accent_primary}`, etc.) based on the active `StyleMode`.

---

## Style Modes

`qthemer` provides three distinct styling modes via `StyleMode`:

```python
from qthemer import StyleMode

# Set during initialization
manager = ThemeManager(style_mode=StyleMode.MINIMAL)

# Or change at runtime
manager.set_style_mode(StyleMode.FULL)
```

| Mode | Identifier | Description | Best For |
| :--- | :--- | :--- | :--- |
| **`FULL`** | `"full"` | Injects a complete custom QSS stylesheet covering buttons, inputs, tabs, sliders, docks, menus, and views. | Modern standalone tools, consumer desktop applications, cohesive custom styling. |
| **`MINIMAL`** | `"minimal"` | Styles only window chrome (dock panels, tab bars, splitters, scrollbars, headers, tooltips, group boxes). Leaves buttons, line edits, and spinboxes to native Fusion metrics. | Complex desktop tools, large control panels, CAD/data dashboards. |
| **`PALETTE`** | `"palette"` | No QSS stylesheet injected. Uses `QPalette` roles and vector SVG standard icons only. | Maximum performance, native accessibility compliance, or legacy widgets with embedded QSS. |

---

## UI Density

In `StyleMode.FULL`, you can adjust control padding, border radii, indicator sizes, and spacing using `Density`:

```python
from qthemer import Density

# Set during initialization
manager = ThemeManager(density=Density.COMPACT)

# Or change at runtime
manager.set_density(Density.COMFORTABLE)
```

| Preset | Identifier | Description |
| :--- | :--- | :--- |
| **`COMPACT`** | `"compact"` | Tighter padding, smaller radii, and compact rows for information-dense panels and dashboards. |
| **`NORMAL`** | `"normal"` | Balanced default metrics suitable for most desktop applications. |
| **`COMFORTABLE`** | `"comfortable"` | Extra breathing room, taller touch/click targets, and wider spacing. |

---

## Bundled Themes

`qthemer` ships with 8 curated dark and light themes:

| Identifier | Display Name | Dark/Light |
| :--- | :--- | :--- |
| `catppuccin_mocha` *(default dark)* | Catppuccin Mocha | Dark |
| `catppuccin_latte` *(default light)* | Catppuccin Latte | Light |
| `dracula` | Dracula | Dark |
| `gruvbox_dark` | Gruvbox Dark | Dark |
| `nord` | Nord | Dark |
| `one_dark` | One Dark | Dark |
| `solarized_light` | Solarized Light | Light |
| `tokyo_night` | Tokyo Night | Dark |
| `system` *(dynamic)* | System Default | Mirrors OS appearance |

### Operating System Theme Tracking (`system`)

Setting the theme to `"system"` dynamically binds `qthemer` to the host OS color scheme:

```python
manager.set_theme("system")
```

When macOS, Windows, or Linux switches between Dark and Light appearances, `ThemeManager` catches the change via `QStyleHints.colorSchemeChanged` and re-applies the configured `dark_theme` or `light_theme`.

---

## Semantic Color Tokens

Each theme defines a structured token hierarchy with automatic fallback resolution:

```
tokens
├── surface
│   ├── window        # Main window, dock, and panel background
│   ├── inset         # Recessed surfaces: inputs, tables, lists, editors, canvases
│   ├── control       # Interactive surfaces: buttons, headers, tooltips, alternating rows
│   ├── border        # Divider lines and borders
│   └── border_focus  # Focused input border (defaults to border)
├── text
│   ├── primary       # High-contrast readable foreground text
│   ├── muted         # Secondary, placeholder, and helper text
│   └── disabled      # Disabled controls and inactive labels
├── accent
│   ├── primary       # Primary highlights, active tab lines, focused borders
│   ├── text          # Text drawn on accent backgrounds
│   └── selection     # Selected list/table item background
├── status
│   ├── trace         # Fine-grained trace logs (defaults to text.disabled)
│   ├── debug         # Debug logs (defaults to text.muted)
│   ├── info          # Info notices (defaults to accent.primary)
│   ├── success       # Connected / normal / ready state
│   ├── warning       # Caution / warning state
│   ├── error         # Error / failure state
│   └── critical      # Critical alert / fatal state (defaults to error)
└── plot
    ├── background    # Plot canvas background (defaults to surface.inset)
    ├── foreground    # Axis labels, titles, tick labels, and legend text (defaults to text.primary)
    ├── grid          # Coordinate grid lines (defaults to surface.control)
    ├── axis          # Axis spines and tick marks (defaults to text.muted)
    └── trace_colors  # Sequence of distinct curve colors for multi-curve plotting
```

### Accessing Tokens in Code

```python
# Hex string lookup
window_hex = manager.theme.get_color("surface.window")  # '#1e1e2e'
accent_hex = manager.theme.tokens.accent.primary  # '#cba6f7'

# QColor lookup
qcolor = manager.theme.get_qcolor("accent.primary")
```

---

## Creating Custom Themes

Themes can be defined as **TOML** files, **JSON** files, or Python dictionaries.

### TOML Format Example

`qthemer` supports an optional `[palette]` table. You can define base colors once in `[palette]` and reference them in `[tokens]` using `$name` syntax:

```toml
# custom_theme.toml
name = "cyberpunk_dark"
display_name = "Cyberpunk Dark"
is_dark = true

[palette]
yellow = "#fcee0a"
cyan = "#00f0ff"
black = "#0d0d0d"
dark_gray = "#1a1a1a"
mid_gray = "#2d2d2d"
white = "#f0f0f0"
muted = "#7a7a7a"
red = "#ff003c"
green = "#00ff66"

[tokens.surface]
window = "$black"
inset = "$dark_gray"
control = "$mid_gray"
border = "$cyan"
border_focus = "$yellow"

[tokens.text]
primary = "$white"
muted = "$muted"
disabled = "#444444"

[tokens.accent]
primary = "$yellow"
text = "$black"
selection = "$mid_gray"

[tokens.status]
success = "$green"
warning = "$yellow"
error = "$red"

# [tokens.plot] is optional: it will automatically inherit from surface and text
```

### Registering Themes in Python

You can register themes from file paths, dictionaries, or `Theme` instances:

```python
# 1. From a file path (.toml or .json)
manager.register_theme("path/to/custom_theme.toml")

# 2. From a dictionary
manager.register_theme(
    {
        "name": "simple_dark",
        "display_name": "Simple Dark",
        "is_dark": True,
        "tokens": {
            "surface": {
                "window": "#1e1e1e",
                "inset": "#121212",
                "control": "#252525",
                "border": "#333333",
            },
            "text": {
                "primary": "#ffffff",
                "muted": "#aaaaaa",
                "disabled": "#555555",
            },
            "accent": {
                "primary": "#3399ff",
                "text": "#ffffff",
                "selection": "#1a4066",
            },
            "status": {
                "success": "#00ff00",
                "warning": "#ffaa00",
                "error": "#ff0000",
            },
        },
    }
)

# 3. Switch to it immediately
manager.set_theme("cyberpunk_dark")
```

---

## UI Components & Actions

`qthemer` includes pre-built PySide6 UI helpers:

### 1. Dark/Light Toggle Action (`create_toggle_action`)

Creates a `QAction` with a dynamic vector icon that shows a **sun** in dark mode (suggesting a switch to light) and a **moon** in light mode.

```python
toggle_action = create_toggle_action(
    manager,
    parent=main_window,
    text="Toggle Dark/Light",
    shortcut="Ctrl+Shift+T",
)
toolbar.addAction(toggle_action)
```

### 2. Theme Selection Dialog (`ThemeSelectorDialog` / `create_dialog_action`)

A comprehensive modal dialog that includes:
- A theme selector dropdown.
- An isolated live widget preview (`ThemePreviewWidget`) showcasing inputs, buttons, checkboxes, views, headers, and status badges.
- An **Import** button enabling users to import `.toml` and `.json` theme files at runtime.
- **Apply**, **OK**, and **Cancel** buttons.

```python
# As a QAction for menus
view_menu.addAction(create_dialog_action(manager, parent=main_window))

# Or instantiated manually
from qthemer import ThemeSelectorDialog

dialog = ThemeSelectorDialog(parent=main_window, manager=manager)
dialog.exec()
```

### 3. Binding Dynamic Icons (`bind_icon`)

Bind standard Qt pixmap icons to buttons or actions. `qthemer` automatically updates the icon color whenever the theme changes, using weak references to prevent memory leaks:

```python
from PySide6.QtWidgets import QPushButton, QStyle

info_button = QPushButton("Help")
manager.bind_icon(info_button, QStyle.StandardPixmap.SP_MessageBoxInformation)

# When the widget is closed or deleted, it unbinds automatically.
# You can also manually unbind:
manager.unbind_icon(info_button)
```

### 4. Styling Standalone Widgets (`apply_theme_to_widget`)

You can style specific windows, popups, or custom dialogs with an isolated theme without altering the rest of the application:

```python
preview_window = QWidget()
manager.apply_theme_to_widget(preview_window, "catppuccin_latte")
preview_window.show()
```

---

## Dynamic Widget Properties in QSS

`qthemer`'s stylesheet supports custom dynamic properties on standard widgets:

### Headings and Muted Labels

```python
from PySide6.QtWidgets import QLabel

# Bold accent-colored section heading
heading = QLabel("General Settings")
heading.setProperty("variant", "heading")  # or heading.setProperty("heading", True)

# De-emphasized secondary text
helper = QLabel("Values are synchronized every 500ms")
helper.setProperty("variant", "muted")
```

---

## Plotting Integration

`qthemer` includes optional, zero-overhead plot adapters for **`pyqtgraph`** and **`matplotlib`**. Both libraries are imported lazily, so core `qthemer` stays lightweight when neither is installed.

Bind any live plot widget, canvas, figure, axes, or toolbar via `manager.bind_plot(...)` (backed by weak references, mirroring `bind_icon`):

### PyQtGraph Integration

Supports `PlotWidget`, `GraphicsLayoutWidget`, `PlotItem`, and `GraphicsView`:

```python
import pyqtgraph as pg
from qthemer.plots.pyqtgraph import trace_pen

plot_widget = pg.PlotWidget(title="Sensor Drift")
plot_widget.showGrid(x=True, y=True, alpha=0.35)
plot_widget.addLegend()

# Auto-cycle through theme trace colors (or pass an explicit int index)
plot_widget.plot(x, y1, pen=trace_pen(manager.theme, plot_widget, width=2), name="Ch 1")
plot_widget.plot(x, y2, pen=trace_pen(manager.theme, plot_widget, width=2), name="Ch 2")

# Auto-retheme background, axes, title, legend, and (optionally) existing curves
manager.bind_plot(plot_widget, recolor_traces=True)
```

### Matplotlib Integration

Supports `FigureCanvasQTAgg` / `FigureCanvasBase`, `Figure`, `Axes`, and `NavigationToolbar2QT`:

```python
import matplotlib as mpl
from matplotlib.backends.backend_qtagg import (
    FigureCanvasQTAgg,
    NavigationToolbar2QT,
)
from matplotlib.figure import Figure
from qthemer.plots.matplotlib import build_matplotlib_rcparams

fig = Figure(figsize=(5, 4), tight_layout=True)
canvas = FigureCanvasQTAgg(fig)
toolbar = NavigationToolbar2QT(canvas, parent=window)

ax = fig.add_subplot(111)
ax.plot(x, y1, label="Ch 1")
ax.plot(x, y2, label="Ch 2")
ax.grid(True)
ax.legend()

# Live runtime retheming (uses non-blocking canvas.draw_idle())
manager.bind_plot(canvas, recolor_traces=True)
manager.bind_plot(toolbar)

# Or use rc_context for one-shot offscreen / static figures:
with mpl.rc_context(build_matplotlib_rcparams(manager.theme)):
    ...
```

### Global Defaults & Custom Backends

- Pass `sync_plot_defaults=True` to `ThemeManager(...)` (or call `manager.sync_plot_defaults()`) to keep `pyqtgraph.setConfigOptions` and `matplotlib.rcParams` synced with theme changes for newly created plots.
- Implement the `PlotAdapter` protocol (`can_handle(target)` + `apply(target, theme, **options)`) and register it with `register_plot_adapter(adapter)` to support additional plotting libraries.

---

## Interactive Demo & Examples

To test all themes, widget controls, style modes, density presets, standard icons, dialogs, and optional live plots, run the interactive demo workbench:

```bash
# Using the installed script entry point:
qthemer-demo

# Or via Python module execution:
python -m qthemer
```

Additional runnable examples are included under `examples/`:
- [`examples/quickstart.py`](https://github.com/tugatoconhelado/qthemer/blob/main/examples/quickstart.py) — minimal application with theme toggle and selector dialog.
- [`examples/plots_demo.py`](https://github.com/tugatoconhelado/qthemer/blob/main/examples/plots_demo.py) — side-by-side live PyQtGraph and Matplotlib theme preview.

---

## API Reference

### `ThemeManager`

```python
class ThemeManager(QObject):
    def __init__(
        self,
        initial_theme: str = "catppuccin_mocha",
        *,
        themes: Iterable[Theme | dict[str, Any] | str | Path] | None = None,
        light_theme: str = "catppuccin_latte",
        dark_theme: str = "catppuccin_mocha",
        settings_key: str = "theme/active_theme",
        auto_save: bool = True,
        apply_on_init: bool = True,
        style_mode: StyleMode | str = StyleMode.FULL,
        density: Density | str = Density.NORMAL,
        sync_plot_defaults: bool = False,
        settings: QSettings | None = None,
        parent: QObject | None = None,
    ) -> None: ...
```

#### Signals
- **`theme_changed(str)`**: Emitted whenever the active theme changes, sending the new theme identifier.

#### Properties
- **`theme -> Theme`**: Currently active `Theme` instance.
- **`available_themes -> list[str]`**: List of all registered theme identifiers (including `"system"`).
- **`stylesheet -> str`**: Currently applied QSS stylesheet string.
- **`style_mode -> StyleMode`**: Currently active styling mode (`FULL`, `MINIMAL`, or `PALETTE`).
- **`density -> Density`**: Currently active UI density preset (`COMPACT`, `NORMAL`, or `COMFORTABLE`).

#### Core Methods
- **`set_theme(name: str, *, force: bool = False) -> bool`**: Switch active theme.
- **`toggle_dark_light() -> str`**: Toggle between configured dark and light themes. Returns active theme name.
- **`set_style_mode(mode: StyleMode | str) -> bool`**: Switch styling mode (`FULL`, `MINIMAL`, `PALETTE`).
- **`set_density(density: Density | str) -> bool`**: Switch UI density preset (`COMPACT`, `NORMAL`, `COMFORTABLE`).
- **`set_stylesheet(stylesheet: str | None = None) -> None`**: Override the QSS template in `FULL` mode, or pass `None` to restore the built-in template.
- **`register_theme(theme, *, overwrite: bool = True) -> Theme`**: Register a theme from a file path, dict, or `Theme` object.
- **`get_theme(name: str) -> Theme`**: Look up registered `Theme` by name.
- **`apply_theme_to_widget(widget: QWidget, theme_name: str | None = None) -> None`**: Apply a theme locally to a specific widget tree.
- **`get_icon(source: IconSource, *, color="text.primary") -> QIcon`**: Resolve a themed vector `QIcon` on demand.
- **`bind_icon(target: QAction | QAbstractButton | QSystemTrayIcon, source, *, color="text.primary", dark=None, light=None) -> None`**: Auto-updating vector icon binding.
- **`unbind_icon(target: QAction | QAbstractButton | QSystemTrayIcon) -> None`**: Unbind previously tracked icon.
- **`bind_plot(target, *, recolor_traces: bool = False, **options) -> None`**: Bind a PyQtGraph, Matplotlib, or custom-adapted plot for live retheming.
- **`unbind_plot(target) -> None`**: Unbind previously tracked plot.
- **`trace_pen(target, **pen_kwargs) -> QPen`**: Construct a PyQtGraph `QPen` from the active theme's trace palette (accepts an `int` index, `PlotWidget`, or `PlotItem`).
- **`sync_plot_defaults(*, pyqtgraph=None, matplotlib=None, antialias=None, match_window_bg=True, theme_savefig=False) -> None`**: Sync global PyQtGraph / Matplotlib defaults with the active theme.
- **`save_state() -> None`**: Save active theme name to `QSettings`.
- **`restore_state(default_theme: str = "catppuccin_mocha") -> str`**: Restore and apply theme from `QSettings`.
- **`detect_system_dark_mode(default: bool = True) -> bool`**: Static method checking OS dark mode preference.

---

### `Theme`

```python
class Theme(BaseModel):
    name: str
    display_name: str
    is_dark: bool
    palette: dict[str, str] = {}
    tokens: ColorTokens
```

#### Methods
- **`Theme.from_file(file: str | Path) -> Theme`**: Load from `.toml` or `.json` file.
- **`Theme.from_dict(data: dict[str, Any]) -> Theme`**: Construct from raw dictionary.
- **`Theme.get_builtin_themes() -> dict[str, Theme]`**: Return mapping of all bundled themes.
- **`to_dict() -> dict[str, Any]`**: Serialize to dictionary.
- **`get_color(token_name: str) -> str`**: Look up hex color string by token path or palette key.
- **`get_qcolor(token_name: str) -> QColor`**: Look up `QColor` by token path or palette key.
- **`get_trace_color(index: int) -> str`**: Look up trace hex color at `index` (wraps modulo palette length).
- **`get_trace_qcolor(index: int) -> QColor`**: Look up trace `QColor` at `index` (wraps modulo palette length).

---

### Plot Functions & Adapters

- **`apply_plot_theme(target, theme, *, recolor_traces=False, **options) -> None`**: Stateless plot theming dispatcher.
- **`PlotAdapter`**: Runtime-checkable `Protocol` (`can_handle`, `apply`) for custom plot backends.
- **`register_plot_adapter(adapter) -> None`** / **`unregister_plot_adapter(adapter) -> None`**: Manage custom plot adapters.
- **`qthemer.plots.pyqtgraph`**: `apply_pyqtgraph_theme`, `configure_pyqtgraph`, `trace_pen`.
- **`qthemer.plots.matplotlib`**: `apply_matplotlib_theme`, `build_matplotlib_rcparams`, `configure_matplotlib`.

---

### UI & Icon Helpers

- **`create_toggle_action(manager, parent=None, text="Toggle Dark/Light Theme", shortcut="Ctrl+Shift+T") -> QAction`**
- **`create_dialog_action(manager, parent=None, text="Select Theme...", shortcut=None, import_dir=None, copy_imported=False) -> QAction`**
- **`ThemeSelectorDialog(parent=None, manager=None, import_dir=None, copy_imported=False)`**
- **`clear_icon_cache() -> int`**: Remove cached recolored SVG icons from the temporary cache directory.

---

## Credits

- **Icons**: Bundled SVG icons are sourced from [Lucide](https://lucide.dev/) (ISC License; portions derived from [Feather](https://feathericons.com/), MIT License). See [`src/qthemer/resources/icons/LICENSE`](https://github.com/tugatoconhelado/qthemer/blob/main/src/qthemer/resources/icons/LICENSE).
- **Color Palettes**: Built-in themes are inspired by [Catppuccin](https://catppuccin.com/), [Dracula](https://draculatheme.com/), [Gruvbox](https://github.com/morhetz/gruvbox), [Nord](https://www.nordtheme.com/), [One Dark](https://github.com/atom/atom/tree/master/packages/one-dark-ui), [Solarized](https://ethanschoonover.com/solarized/), and [Tokyo Night](https://github.com/enkia/tokyo-night-vscode-theme).

---

## License

This project is licensed under the MIT License. See [`LICENSE`](https://github.com/tugatoconhelado/qthemer/blob/main/LICENSE) for details.
