Skip to content

API reference

The public API is exactly the names below, which pyside6_storybook.__all__ exports.

Package

ActionSink

Bases: Protocol

Receives the actions a story logs with StoryContext.log, log_signal and log_signals.

The gallery's Actions panel is one.

record

record(name: str, args: tuple[object, ...]) -> None

Record one action.

Parameters:

Name Type Description Default
name str

The action's name, such as "clicked".

required
args tuple[object, ...]

The arguments the action carried.

required

BoolControl dataclass

A boolean argument.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default bool

Initial value.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

Raises:

Type Description
TypeError

If default is not a bool, or label or description has the wrong type.

ValueError

If label is blank.

display_label property

display_label: str

The form label: label, or the label derived from name.

coerce

coerce(value: object) -> bool

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value.

required

Returns:

Type Description
bool

value, which must be a bool; 0 and 1 are not accepted.

Raises:

Type Description
TypeError

If value is not a bool.

BuiltinThemeProvider

Switches a QApplication between the built-in Light, Dark and System themes; the default ThemeProvider.

Activate it once with the application, switch with set_theme and deactivate it to put back what activate found. set_theme can be called before activate; the theme is then applied on activation. set_theme calls the callbacks registered with on_changed before it returns.

theme_names

theme_names() -> tuple[str, ...]

Return the names of the available themes.

current_theme

current_theme() -> str

Return the name of the current theme.

tokens

tokens() -> Mapping[str, object]

Return the design tokens: #rrggbb strings read from the application palette's Active group.

The tokens are window, window_text, base, alternate_base, text, button, button_text, highlight, highlighted_text, accent, border (the Mid role) and placeholder_text. Without a QApplication the mapping is empty.

color_scheme

color_scheme() -> Qt.ColorScheme

Return the colour scheme of the current theme.

Light and Dark give their own scheme. For System it is the scheme Qt reports, or, when Qt reports Unknown (no setting on this platform), a guess from the application palette's Window colour. Without a QApplication System gives Unknown.

on_changed

on_changed(callback: Callable[[], None]) -> None

Register a callback that is called with no arguments after every theme change.

Parameters:

Name Type Description Default
callback Callable[[], None]

What to call. Callbacks are called in the order they were registered.

required

activate

activate(app: QApplication) -> None

Remember the application's style, palette, style sheet and font, find out whether it forced a colour scheme, and apply the current theme.

Parameters:

Name Type Description Default
app QApplication

The application to theme.

required

Raises:

Type Description
RuntimeError

If the themes are already active.

set_theme

set_theme(name: str) -> None

Switch to a theme.

Parameters:

Name Type Description Default
name str

One of theme_names.

required

Raises:

Type Description
ValueError

If name is not a built-in theme.

deactivate

deactivate() -> None

Restore the style, palette, style sheet, font and colour scheme found by activate and clear the callbacks.

Does nothing if not active.

The style is restored by name. A style that was installed as a QStyle instance with no name Qt can create again cannot be restored this way, and Fusion stays in place.

ChoiceControl dataclass

An argument that is one of a fixed list of strings.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default str

Initial value; must be one of options.

options Sequence[str]

The allowed values. Any sequence of strings is accepted; it is stored as a tuple.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

Raises:

Type Description
TypeError

If options is a bare string instead of a sequence of strings, default is not a string, or label or description has the wrong type.

ValueError

If default is not one of options, or label is blank.

display_label property

display_label: str

The form label: label, or the label derived from name.

coerce

coerce(value: object) -> str

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value.

required

Returns:

Type Description
str

value, which must be one of options.

Raises:

Type Description
TypeError

If value is not a string.

ValueError

If value is not one of options.

ColorControl dataclass

A colour argument. The story receives a QColor; the default is a hex string.

The accepted strings are, in either case, exactly #RRGGBB and, with alpha=True, #RRGGBBAA (the CSS byte order, with the alpha byte last). Colour names and the short #RGB form are not accepted.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default str

Initial value, a hex string.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

alpha bool

Allow a translucent colour: the editor's dialog shows an alpha channel and #RRGGBBAA is accepted.

Raises:

Type Description
TypeError

If default is not a string, alpha is not a bool, or label or description has the wrong type.

ValueError

If default is not a valid hex colour for this control, or label is blank.

display_label property

display_label: str

The form label: label, or the label derived from name.

coerce

coerce(value: object) -> QColor

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value: a hex string or a QColor.

required

Returns:

Type Description
QColor

A new QColor on every call.

Raises:

Type Description
TypeError

If value is neither a string nor a QColor.

ValueError

If a string is not a hex colour in this control's grammar, or a QColor is invalid or translucent without alpha=True.

Control module-attribute

Control = (
    TextControl
    | BoolControl
    | ChoiceControl
    | IntControl
    | FloatControl
    | ColorControl
    | EnumControl
    | FileControl
)

Any control type.

Decorator module-attribute

Decorator = Callable[[QWidget, StoryContext], QWidget]

A decorator: receives the widget built so far and the story's context, and returns the widget to show instead. It returns the same widget after configuring it, or a new wrapper that contains the received widget as a descendant.

EnumControl dataclass

An argument that is one of the named members of an enum class, which is the class of default.

Works for Python enums and PySide6's Qt enums. The options are the class's named members in definition order; an alias (a second name for the same value) is left out and the first name is kept. For a Flag the named combinations are options too, for example Qt.AlignmentFlag.AlignCenter, but an unnamed combination such as AlignLeft | AlignTop is not.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default Enum

Initial value; a member of the enum class that is one of options. It also fixes the enum class.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

Raises:

Type Description
TypeError

If default is not an enum member, or label or description has the wrong type.

ValueError

If default is not one of options (an unnamed flag combination), or label is blank.

options property

options: tuple[Enum, ...]

The members the editor offers, in definition order, without aliases.

display_label property

display_label: str

The form label: label, or the label derived from name.

coerce

coerce(value: object) -> Enum

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value.

required

Returns:

Type Description
Enum

The option equal to value.

Raises:

Type Description
TypeError

If value is not an instance of the default's enum class; an int or bool is not accepted, even for an IntEnum or IntFlag class.

ValueError

If value is not one of options.

FileControl dataclass

A file path argument. The story receives a Path, or None while the path is empty.

The file need not exist. A relative path stays relative to the working directory.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default str | Path

Initial value, a string or a Path; the empty string means no file.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

filter str

A QFileDialog name filter for the Browse button, for example "Images (*.png *.jpg)".

Raises:

Type Description
TypeError

If default is neither a string nor a Path, filter is not a string, or label or description has the wrong type.

ValueError

If label is blank.

display_label property

display_label: str

The form label: label, or the label derived from name.

coerce

coerce(value: object) -> Path | None

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value.

required

Returns:

Type Description
Path | None

A Path, or None for None and the empty string.

Raises:

Type Description
TypeError

If value is not a string, a Path or None.

FloatControl dataclass

A floating-point argument within an inclusive range.

The editor shows effective_decimals decimals, so coerce rejects a value that would be rounded by it, and so does the constructor for the default and the bounds. A default or bound that needs more than 10 decimals is therefore rejected.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default float

Initial value; must lie within the range.

minimum float

Smallest allowed value.

maximum float

Largest allowed value.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

step float | None

The editor's single step, > 0 and at most the range; None derives a power of ten near 1% of the range. A zero-width range (minimum == maximum) uses 1.0 and does not accept an explicit step.

decimals int | None

Decimals the editor shows, 0..10; None derives the fewest (at least 2) that represent the step, the default and both bounds exactly.

slider bool

Show a slider beside the spin box. Its positions are 0..slider_steps; position i means min(minimum + i * effective_step, maximum), and the last position is always exactly maximum.

Raises:

Type Description
TypeError

If a value is not a number, decimals is not an integer, slider is not a bool, or label or description has the wrong type.

ValueError

If a value is not finite, minimum > maximum, default is outside the range, step or decimals is out of its range, decimals is too small for the step, the default or a bound, a value needs more than 10 decimals, a slider would have more than 10 000 steps, or label is blank.

display_label property

display_label: str

The form label: label, or the label derived from name.

effective_step property

effective_step: float

The editor's single step: step, or a power of ten near 1% of the range (1.0 for a zero-width range).

effective_decimals property

effective_decimals: int

The decimals the editor shows: decimals, or the fewest (at least 2, at most 10) that represent the step, the default and both bounds exactly.

slider_steps property

slider_steps: int

The number of steps of the slider, which has positions 0..slider_steps: ceil((maximum - minimum) / step - 1e-9).

coerce

coerce(value: object) -> float

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value.

required

Returns:

Type Description
float

value as a float. It must be an int or float (not a bool), finite, within the range, and not

float

changed by rounding to effective_decimals decimals, which is what the editor would do to it.

Raises:

Type Description
TypeError

If value is not an int or float.

ValueError

If value is too large for a float, is not finite, is outside the range, or needs more decimals than the editor shows.

IntControl dataclass

An integer argument within an inclusive range.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default int

Initial value; must lie within the range.

minimum int

Smallest allowed value.

maximum int

Largest allowed value.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

step int

The editor's single step (arrow keys, and the slider's keys); at least 1.

slider bool

Show a slider beside the spin box.

Raises:

Type Description
TypeError

If default, a bound or step is not an integer, slider is not a bool, or label or description has the wrong type.

ValueError

If a bound is outside the signed 32-bit range the editor (QSpinBox) supports, minimum > maximum, default is outside the range, step is below 1, or label is blank.

display_label property

display_label: str

The form label: label, or the label derived from name.

coerce

coerce(value: object) -> int

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value.

required

Returns:

Type Description
int

value, which must be an int within the range.

Raises:

Type Description
TypeError

If value is not an int; a bool is not accepted.

ValueError

If value is outside the range.

Layout

Bases: StrEnum

How the preview places a story's widget.

Members

CENTERED: The widget keeps its natural size and is centred in the preview, horizontally and vertically. PADDED: The widget sits at the top of the preview inside a margin. Its width follows its horizontal size policy, so a button stretches to the full width, and its height is its natural height. FILL: The widget fills the preview inside the margin, in each direction its size policy lets it grow. In a direction it cannot grow, it keeps its natural size and is centred.

A widget larger than the preview scrolls in CENTERED and PADDED; FILL never shows scroll bars.

LoadError dataclass

A story source that could not be loaded.

Attributes:

Name Type Description
source str

The target as given, or the path of the story file, that failed.

message str

A one-line description of the problem.

details str

The formatted traceback when an exception was raised while importing, otherwise an empty string.

target_error bool

True when the target itself is wrong (no file, folder or module has that name, or it is a file that is not Python), as opposed to a story module that failed while importing.

LoadResult dataclass

The outcome of load_stories.

Attributes:

Name Type Description
registry StoryRegistry

The registry the loaded stories registered themselves in (the default registry).

modules tuple[str, ...]

Names of the story modules that were imported or were already imported, in load order, without duplicates. A target given as a dotted name is listed too, whether it is a module or a package, so a package whose stories are in its __init__.py is listed.

errors tuple[LoadError, ...]

The sources that failed, in load order.

SizePreset dataclass

A named size for the gallery's canvas, listed in its Size menu after the built-in sizes.

With a preset selected, the area a story is placed in is exactly width by height pixels.

Attributes:

Name Type Description
name str

The name shown in the Size menu; not blank.

width int

The width in pixels; positive and at most 10 000.

height int

The height in pixels; positive and at most 10 000.

Raises:

Type Description
TypeError

If name is not a string, or width or height is not an int (a bool is not accepted).

ValueError

If name is blank, or width or height is not positive or is above 10 000, the largest size the canvas can show.

Story

A registered story: a function that builds one widget, plus its id and controls.

Story objects are what @story returns. They are callable, so my_story(ctx) still builds the widget.

Attributes:

Name Type Description
id

The unique /-separated path, for example "Inputs/Button".

name

The last segment of id.

groups

The segments of id before the name.

component str | None

The groups joined with / ("Inputs/Button" for "Inputs/Button/Default"), or None without groups.

controls

The story's controls, in order.

decorators tuple[Decorator, ...]

The decorators that wrap the story's widget, the first one outermost. A variant without its own has its base's.

layout Layout | None

The layout the story declared, or None to use the registry's default_layout. A variant without its own layout has its base's.

checks_ignore Mapping[str, str]

The checks the story opts out of, as a read-only mapping from a rule ("name", "focus", "contrast" or "snapshot") to the reason. A variant without its own has its base's.

args Mapping[str, Any]

For a variant, the values it overrides, by control name, as a read-only mapping; empty for any other story.

variant_of Story | None

The base story, for a variant; None otherwise.

doc

The function's docstring, or an empty string.

module

Module the function was defined in.

qualname

Qualified name of the function. For a callable without one (a functools.partial or a callable object), the module and qualified name of its type.

component property

component: str | None

The groups joined with / ("Inputs/Button" for "Inputs/Button/Default"), or None without groups.

function property

function: StoryFunction

The callable the story was created with; a variant has its base's.

args property

args: Mapping[str, Any]

For a variant, the values it overrides, by control name, as a read-only mapping; empty for any other story.

variant_of property

variant_of: Story | None

The base story, for a variant; None otherwise.

origin property

origin: StoryOrigin

The module and qualified name the story function was defined in.

__init__

__init__(
    id: str,
    function: StoryFunction,
    *,
    controls: Iterable[Control] = (),
    layout: Layout | str | None = None,
    decorators: Iterable[Decorator] = (),
    checks_ignore: Mapping[str, str] = NO_CHECKS_IGNORED,
) -> None

Create a story.

Parameters:

Name Type Description Default
id str

A non-empty /-separated path without empty segments.

required
function StoryFunction

The function that builds the widget.

required
controls Iterable[Control]

The story's controls.

()
layout Layout | str | None

How the gallery places the widget in the preview: a Layout, its string value, or None for the registry's default_layout.

None
decorators Iterable[Decorator]

Functions that wrap the widget, the first one outermost; see Decorator.

()
checks_ignore Mapping[str, str]

Rules of the pytest plugin's checks the story opts out of, each with the reason: {"focus": "decorative"}. The rules are "name", "focus", "contrast" and "snapshot".

NO_CHECKS_IGNORED

Raises:

Type Description
ValueError

If id is empty or has an empty segment, two controls share a name, layout is not valid, or checks_ignore names an unknown rule or has an empty reason.

TypeError

If an item of controls is not a control, decorators is not a collection of callables, or checks_ignore is not a mapping.

default_args

default_args() -> dict[str, object]

Return the value every control starts with, keyed by control name.

Each value is the variant's value for the control, or the control's default, passed through the control's coerce, so it has the type a story receives. Every call returns new objects.

variant

variant(
    name: str,
    *,
    args: Mapping[str, object] | None = None,
    layout: Layout | str | None = None,
    decorators: Iterable[Decorator] | None = None,
    checks_ignore: Mapping[str, str] | None = None,
) -> Story

Register a variant of this story: the same function and controls, with other starting values.

The variant's id is the component plus name ("Inputs/Button/Disabled"), and it comes after this story in the registry. Calling this twice with the same name replaces the first variant.

Parameters:

Name Type Description Default
name str

The variant's name: not blank, without /, and different from this story's name.

required
args Mapping[str, object] | None

Values that replace control defaults, by control name. Each must be accepted by its control's coerce.

None
layout Layout | str | None

The variant's layout; None keeps this story's.

None
decorators Iterable[Decorator] | None

The variant's decorators, which replace this story's; None keeps them.

None
checks_ignore Mapping[str, str] | None

The variant's check opt-outs, which replace this story's; None keeps them.

None

Returns:

Type Description
Story

The registered variant.

Raises:

Type Description
TypeError

If this story is itself a variant.

RuntimeError

If this story was never registered.

ValueError

If this story's id has no group, name is invalid, args has an unknown key or an invalid value, layout is not valid, or checks_ignore names an unknown rule or has an empty reason.

TypeError

Also if decorators is not a collection of callables or checks_ignore is not a mapping.

__call__

__call__(ctx: StoryContext) -> QWidget

Build the story's widget.

Parameters:

Name Type Description Default
ctx StoryContext

The context to pass to the story function.

required

Returns:

Type Description
QWidget

Whatever the story function returns.

StoryContext dataclass

Everything a story function receives.

Attributes:

Name Type Description
args Mapping[str, Any]

The current control values by control name. Stored as a read-only copy. Typed Any so a story can pass a value straight to Qt (QSpinBox.setValue(ctx.args["count"])); each value has the type of its control's default.

theme str

Name of the active theme.

actions ActionSink | None

Where log, log_signal and log_signals send actions. The gallery passes its Actions panel; it is None otherwise, and then all three methods do nothing. It does not take part in equality or repr.

tokens Mapping[str, Any]

The design tokens of the active theme, by name, as the theme provider returns them from its optional tokens() method (the built-in themes give colours such as "accent" as #rrggbb strings). Stored as a read-only copy and empty by default, so a story reads ctx.tokens.get("accent") and handles a missing token. It does not appear in repr.

color_scheme ColorScheme

Whether the active theme is light or dark, as a Qt.ColorScheme. The theme provider gives it through its optional color_scheme() method; without one the gallery guesses from the application palette's Window colour. Qt.ColorScheme.Unknown by default.

log_signal

log_signal(
    signal: SignalInstance, name: str | None = None
) -> None

Show every emission of signal in the gallery's Actions panel. Without a sink this does nothing.

log_signals does this for every signal of an object. The row shows the arguments the signal delivers to a slot: QPushButton.clicked delivers none, valueChanged delivers the new value. The connection ends when the signal's widget is deleted, and the slot holds no reference to the widget.

Parameters:

Name Type Description Default
signal SignalInstance

A bound signal, such as button.clicked.

required
name str | None

The name to show; the signal's own name when omitted.

None

Raises:

Type Description
TypeError

If there is a sink and name is omitted and the signal's name cannot be found.

log_signals

log_signals(
    obj: QObject, *, exclude: Iterable[str] = ()
) -> None

Show every emission of every signal of obj in the gallery's Actions panel. Without a sink this does nothing.

It logs the signals that the classes of obj declare, below QWidget for a widget (clicked, toggled, valueChanged) and below QObject for any other object (the selectionChanged of an item view's selectionModel()), and leaves out the ones every widget has (objectNameChanged, windowTitleChanged, customContextMenuRequested) and updateRequest, which fires on every repaint. Use log_signal for one of those. Each signal is logged as log_signal logs it, with the arguments of its default overload.

Call it after configuring the object, or the emissions of the setup (addItems emits currentIndexChanged) are logged on every render. The connections end when obj is deleted, so an object that outlives the story's widget gets one more connection per render. Calling it twice connects twice. A signal whose argument type PySide6 cannot convert is not connected, and one warning names it.

Parameters:

Name Type Description Default
obj QObject

The object whose signals to log, such as the widget the story returns, or a child of it.

required
exclude Iterable[str]

Names of signals to leave out, such as ("highlighted",). A name that obj has no signal of is logged as a warning that lists its signals, and does not raise, because the signals differ between Qt versions.

()

Raises:

Type Description
TypeError

If there is a sink and exclude is a string, or obj is not a QObject. A bound signal gets a message that points to log_signal.

log

log(name: str, *args: object) -> None

Show an action in the gallery's Actions panel. Without a sink this does nothing.

Parameters:

Name Type Description Default
name str

The action's name.

required
*args object

The arguments to show.

()

StoryRegistry

An ordered collection of stories, unique by id.

Attributes:

Name Type Description
decorators list[Decorator]

Decorators applied to every story of this registry, outside the story's own, the first one outermost. A plain list that is read at render time, so a project may append to it after its stories are registered.

size_presets list[SizePreset]

Named canvas sizes that the gallery's Size menu lists after its built-in sizes. Empty by default. A plain list that the window reads when it is built and again in GalleryWindow.set_registry, so a project may append to it.

default_layout property writable

default_layout: Layout

The layout of every story that declares none; Layout.PADDED until set.

Assigning a Layout or its string value changes it, before or after stories register; anything else raises ValueError.

register

register(story: Story) -> Story

Add a story.

Registering an id again from the same module and qualified name (a module imported twice or reloaded) replaces the earlier story and keeps its position. The story remembers this registry, so that Story.variant can register variants here.

Parameters:

Name Type Description Default
story Story

The story to add.

required

Returns:

Type Description
Story

story.

Raises:

Type Description
ValueError

If the id is already registered by a different function.

get

get(story_id: str) -> Story

Return the story with the given id.

Parameters:

Name Type Description Default
story_id str

The id to look up.

required

Returns:

Type Description
Story

The story.

Raises:

Type Description
KeyError

If no story has that id.

ids

ids() -> list[str]

Return every story id in registration order.

story

story(
    id: str,
    *,
    controls: Iterable[Control] = (),
    layout: Layout | str | None = None,
    decorators: Iterable[Decorator] = (),
    checks_ignore: Mapping[str, str] = NO_CHECKS_IGNORED,
) -> Callable[[StoryFunction], Story]

Return a decorator that turns a function into a story registered here.

Parameters:

Name Type Description Default
id str

The story id, see Story.

required
controls Iterable[Control]

The story's controls.

()
layout Layout | str | None

The story's layout: a Layout, its string value, or None for default_layout.

None
decorators Iterable[Decorator]

Functions that wrap the story's widget, the first one outermost; see Decorator.

()
checks_ignore Mapping[str, str]

Rules of the pytest plugin's checks the story opts out of, each with the reason: {"focus": "decorative"}. The rules are "name", "focus", "contrast" and "snapshot".

NO_CHECKS_IGNORED

Returns:

Type Description
Callable[[StoryFunction], Story]

A decorator returning the registered Story.

Raises:

Type Description
ValueError

If layout is not valid, or checks_ignore names an unknown rule or has an empty reason; raised here, when the decorator is created.

TypeError

If checks_ignore is not a mapping; raised here too.

TypeError

If decorators is not a collection of callables; raised when the story is registered.

TextControl dataclass

A text argument.

Attributes:

Name Type Description
name str

Argument name, the key in StoryContext.args.

default str

Initial value.

label str | None

Text of the form label; None derives it from name.

description str

Tooltip and accessible description of the editor.

multiline bool

Edit the text in a multi-line editor instead of a single-line one.

Raises:

Type Description
TypeError

If default is not a string, label or description has the wrong type, or multiline is not a bool.

ValueError

If label is blank.

display_label property

display_label: str

The form label: label, or the label derived from name.

coerce

coerce(value: object) -> str

Return value as this control's value type.

Parameters:

Name Type Description Default
value object

A candidate value.

required

Returns:

Type Description
str

value, which must be a string.

Raises:

Type Description
TypeError

If value is not a string.

ThemeProvider

Bases: Protocol

Applies themes to the application and tells the gallery when the theme changed.

The gallery calls every method on the main thread, and a provider calls its callbacks on it too. The lifecycle:

  1. theme_names and current_theme work before activate. theme_names is not empty and does not change while the provider is active.
  2. activate is called once, before the window is built. It records whatever the provider will change (style, palette, style sheet, font, colour scheme) and applies the current theme.
  3. set_theme applies a theme and raises ValueError for a name that theme_names does not list.
  4. on_changed registers a callback that the provider calls with no arguments after every theme change, whether the gallery asked for it or the provider made it itself. Several callbacks may be registered and are called in order.
  5. deactivate undoes everything activate and set_theme changed, the font included, and clears the callbacks. A provider can be activated again after deactivate: the pytest plugin activates it before the first story test, deactivates it when the next test is not a story test and activates it again for the next one.
  6. A provider that sets an application-wide style sheet also sets a matching QPalette: the gallery chrome is drawn from palette roles, and a style sheet alone leaves QApplication.palette() unchanged.
  7. tokens() -> Mapping[str, object] is optional and not part of this protocol, so a provider without it still satisfies it. When present, the gallery reads it after activate and after every change notification and gives the result to each story as StoryContext.tokens; a provider without it gives stories an empty mapping.
  8. color_scheme() -> Qt.ColorScheme is optional and not part of this protocol either. When present, the gallery reads it with the tokens and gives the result to each story as StoryContext.color_scheme. Without it the gallery guesses: Dark when the application palette's Window colour has a lightness below 128, otherwise Light.

theme_names

theme_names() -> Sequence[str]

Return the names of the available themes, in the order the theme switch lists them.

current_theme

current_theme() -> str

Return the name of the current theme.

activate

activate(app: QApplication) -> None

Record what the provider will change on app and apply the current theme.

set_theme

set_theme(name: str) -> None

Apply a theme and notify the callbacks.

Raises:

Type Description
ValueError

If name is not one of theme_names.

on_changed

on_changed(callback: Callable[[], None]) -> None

Register a callback that is called with no arguments after every theme change.

deactivate

deactivate() -> None

Restore everything activate and set_theme changed and clear the registered callbacks.

__version__ module-attribute

__version__ = version('pyside6-storybook')

default_registry module-attribute

default_registry = StoryRegistry()

The process-wide registry that the module-level story decorator registers into.

load_stories

load_stories(
    targets: Iterable[str | PathLike[str]],
    *,
    cwd: str | PathLike[str] | None = None,
) -> LoadResult

Import the story modules named by targets; their @story decorators register the stories.

Each target is, in this order of precedence:

  • an existing folder: every *_story.py and *_stories.py file below it is loaded, skipping test_* files, hidden folders, __pycache__ and virtual environments;
  • an existing .py file: that file is loaded;
  • a dotted module name: the module is imported, and for a package also its submodules named *_story or *_stories in it and in its regular subpackages (again skipping test_* files).

A file inside a package (its folder has __init__.py) is imported under its full dotted name, with the folder above the topmost package on sys.path, so relative imports work and a file reached by path and by module name is one module. A file outside any package is imported under its own name with its folder on sys.path, so siblings can import it and share the module; it gets a synthetic name derived from its path only when its own name is taken by another file. A file whose module name refers to a different file is reported without being executed. cwd is put on sys.path too, as python -m does, so stories can import the application.

Importing runs the code in those modules, exactly as running a test suite does.

Parameters:

Name Type Description Default
targets Iterable[str | PathLike[str]]

Folders, files and dotted module names. Relative paths are resolved against cwd. Duplicates are ignored.

required
cwd str | PathLike[str] | None

The working directory; defaults to the process's current directory.

None

Returns:

Type Description
LoadResult

The registry the stories registered in, the modules loaded, and the targets or files that failed. A failure never stops

LoadResult

the remaining targets from loading.

run

run(
    registry: StoryRegistry | None = None,
    argv: Sequence[str] | None = None,
    *,
    theme: str | None = None,
    load_errors: Sequence[LoadError] = (),
    reload: ReloadSession | None = None,
    theme_provider: ThemeProvider | None = None,
) -> int

Open the gallery window and run the event loop until it closes.

Creates the QApplication (an existing one is reused), activates the theme provider for the duration of the run and deactivates it afterwards. A provider that leaves the application's style, palette, style sheet or font changed is reported in a logged warning; the properties are not fixed.

Parameters:

Name Type Description Default
registry StoryRegistry | None

The stories to show. Defaults to default_registry.

None
argv Sequence[str] | None

Command-line arguments for QApplication. Defaults to sys.argv.

None
theme str | None

The theme to start in, one of the provider's theme_names(). Defaults to the provider's current theme. It is applied through the window once it is built, so a provider that fails to apply it shows the error in the gallery.

None
load_errors Sequence[LoadError]

Story sources that failed to load, listed in the gallery under "Load errors".

()
reload ReloadSession | None

What to load again when a story file changes; the command line passes it. Internal. Without it, nothing is reloaded.

None
theme_provider ThemeProvider | None

Supplies and applies the themes. Defaults to a new BuiltinThemeProvider.

None

Returns:

Type Description
int

The exit code of the event loop.

Raises:

Type Description
ValueError

If theme is not one of the provider's theme names.

story

story(
    id: str,
    *,
    controls: Iterable[Control] = (),
    layout: Layout | str | None = None,
    decorators: Iterable[Decorator] = (),
    checks_ignore: Mapping[str, str] = NO_CHECKS_IGNORED,
) -> Callable[[StoryFunction], Story]

Turn a function into a story registered in default_registry.

Parameters:

Name Type Description Default
id str

A /-separated path such as "Inputs/Button"; the last segment is the story's name.

required
controls Iterable[Control]

The story's controls.

()
layout Layout | str | None

How the gallery places the widget in the preview: a Layout, its string value, or None for the registry's default_layout.

None
decorators Iterable[Decorator]

Functions that wrap the story's widget, the first one outermost; see Decorator.

()
checks_ignore Mapping[str, str]

Rules of the pytest plugin's checks the story opts out of, each with the reason: {"focus": "decorative"}. The rules are "name", "focus", "contrast" and "snapshot".

NO_CHECKS_IGNORED

Returns:

Type Description
Callable[[StoryFunction], Story]

A decorator returning the registered Story.

Raises:

Type Description
ValueError

If layout is not valid, or checks_ignore names an unknown rule or has an empty reason.

TypeError

If checks_ignore is not a mapping.

Checks

The checks in pyside6_storybook.checks, which the pytest plugin runs on every story.

CheckIssue dataclass

One problem found in one widget.

Attributes:

Name Type Description
rule str

The rule that failed, such as "name" or "focus"; the same names checks_ignore takes.

widget_class str

The class name of the widget.

object_name str

The widget's objectName(), or an empty string.

path str

The class names from the checked widget down to this one, each below the root with its index among the siblings of the same class, for example QWidget/QGroupBox[0]/QToolButton[1].

message str

What is wrong and how to fix it.

check_accessible_names

check_accessible_names(widget: QWidget) -> list[CheckIssue]

Find the controls in widget that have no accessible name, which a screen reader cannot announce.

The widget itself and its visible, enabled descendants are checked when they are buttons, line and text edits, spin boxes, combo boxes, sliders, item views or tab bars, or take focus with the Tab key. A name is what a screen reader reads: the widget's text, the text of a buddy label, or setAccessibleName; a tooltip is not a name. A combo box needs setAccessibleName or a buddy label, because its current text does not count. The tabs of a tab widget are checked through their texts. The internals of composite widgets (the line edit of a spin box, the headers and scroll bars of an item view, the tab bar of a tab widget) are not checked.

Parameters:

Name Type Description Default
widget QWidget

The widget to check, with everything in it.

required

Returns:

Type Description
list[CheckIssue]

The issues, in the order the widgets are found; empty when every control has a name.

check_keyboard_focus

check_keyboard_focus(widget: QWidget) -> list[CheckIssue]

Find the controls in widget that the Tab key cannot reach.

The same widgets are checked as in check_accessible_names; each must have a focus policy that includes Qt.FocusPolicy.TabFocus.

Parameters:

Name Type Description Default
widget QWidget

The widget to check, with everything in it.

required

Returns:

Type Description
list[CheckIssue]

The issues, in the order the widgets are found; empty when every control takes focus with Tab.

check_text_contrast

check_text_contrast(
    widget: QWidget,
    *,
    normal: float = DEFAULT_NORMAL,
    large: float = DEFAULT_LARGE,
    include_disabled: bool = False,
) -> list[CheckIssue]

Find the text in widget that is too faint against its background, measured on the pixels that are drawn.

widget should be shown, and its focus cleared, because the check renders it once with QWidget.render into an image and measures that. Pixels, not palette roles, so a widget styled by a style sheet or painted by hand is measured as it looks. For each visible text-bearing descendant (and the widget itself) the check takes the text's own box inside its container, finds the most frequent colour there (the background) and, among the colours that cover at least 3 pixels, the one with the highest contrast ratio against it (the text). A box that holds only one colour fails: the text is drawn in the background colour, or not at all.

The text of labels (without a pixmap), buttons, line edits, spin boxes and combo boxes is checked, and up to 50 visible items of each list, table and tree. Large text (at least 18 pt, or at least 14 pt and bold) needs large, other text normal. Progress-bar text, group box titles, header text, placeholder text and text that a widget paints itself are not checked, and text on a gradient or an image, or very thin text, gives an estimate.

Parameters:

Name Type Description Default
widget QWidget

The widget to check, with everything in it.

required
normal float

The contrast ratio that normal text needs. WCAG AA asks for 4.5.

DEFAULT_NORMAL
large float

The contrast ratio that large text needs. WCAG AA asks for 3.

DEFAULT_LARGE
include_disabled bool

Whether disabled widgets are checked too; their text is faint by design, so they are skipped by default.

False

Returns:

Type Description
list[CheckIssue]

The issues, in the order the widgets are found; empty when every text passes. An issue names the widget, the two colours as

list[CheckIssue]

#rrggbb, the measured ratio, the threshold and whether the text is large.