Skip to content

redsun.qt

Session

QtSession

QtSession(
    config: Source | Sequence[Source] | None = None,
    *,
    log_level: int | str | None = None,
    profile: ProfileKind | None = None,
    profile_dir: str | Path | None = None,
)

Bases: DesktopSession[QMainWindow], Session

Application container whose views are attached to a Qt main window.

Subclass this rather than redsun.Session to build against Qt: it accepts the placements Qt attaches and refuses the rest when the declarations are read. Importing it needs the Qt bindings.

The base container builds the components; this one puts them in a window. Constructing the container touches no toolkit object and reads no file: the application, the async backend and the window are all made by build.

class MyApp(QtSession):
    image: AsView[ImageView]


MyApp().run()

Prepare an empty container, to be filled by build.

The keywords are those of Session.

garbage_interval class-attribute

garbage_interval: int = 100

Milliseconds between two checks of Python's garbage.

From build to shutdown, Python's automatic garbage collection is off and the running Qt event loop collects instead, every this many milliseconds, on the GUI thread; while the event loop doesn't run, nothing is collected.

main_window property

main_window: QModelMainWindow

The window the views are attached to.

It is built against model, so a menu bar or a toolbar filled from that application's registries can be asked for on it.

Raises:

Type Description
RuntimeError

If read before build, which is where it is created.

view_arguments property

view_arguments: Mapping[str, object]

The main window, as every view's parent.

app property

app: QApplication

The toolkit application this session runs on, and keeps alive.

The session keeps a reference to one it created until it is released.

Raises:

Type Description
RuntimeError

If read before build, which is where it is put in place.

model property

model: Application

The application this session's commands and menus are registered on.

Raises:

Type Description
RuntimeError

If read before build, which is where it is created.

start_runtime

start_runtime() -> None

Put the toolkit in place, before the first component is built.

A QApplication has to exist before any widget is constructed, so it is made here. The hooks were resolved by the step before this one, so one may supply the QApplication itself. The session's own application follows, because the components are built out of the registry its store reads, and the actions section is registered on it at once, so a hook dressing the window finds every command it may put in a menu. The window comes next, since every view is built as its child. The colour scheme is asked for before any widget exists to be painted in the wrong one, and a configure_application hook runs last, so one restyling the application does so over a scheme already in force. Each of them registers how it is given back as it is taken, so shutdown frees the name without this class defining one.

Raises:

Type Description
HookError

If the create_application provider could not be built, or returns anything but a QApplication.

build_views

build_views() -> None

Build the views as children of the main window.

A view that fails after handing itself to the window as a child would be shown with it, so what it left behind is deleted.

present

present() -> None

Put every view where it asks to be in the window, and ready the window to show.

A view that failed to build and asked for a dock or the centre is replaced there by a widget naming it and the reason. When any component failed to build or to be set up, or a hook provider was skipped, a button in the status bar counts them and lists them with their tracebacks. The keyboard shortcuts are bound before the main-view hook runs, so the menus it builds show them. A Window menu, added after the hook has run, shows or hides each dock, puts every dock back where its placement says, and lists the shortcuts.

restore_layout

restore_layout() -> None

Put the window back where this user last left it.

Runs once every dock exists, since Qt places a dock by object name and ignores one it has not seen. The geometry always comes back. The docks come back only while the views ask for the places they asked for when the layout was saved, so a changed placement shows on the next run; a layout saved without that record is restored. The centre's splitters and current tabs come back with the docks.

save_layout

save_layout() -> None

Remember where this user left the window, and the placements it was left with.

run asks for this as the session ends, so a window that was shown is the only one that writes.

set_shortcuts

set_shortcuts(changes: Mapping[str, Sequence[str]]) -> None

Save the user's keys, then move them onto the window's commands at once.

Raises:

Type Description
ValueError

If a command is given more than two keys, a key Qt cannot bind, or belongs to a view the window holds no action for; nothing is saved or moved then.

reset_shortcuts

reset_shortcuts() -> None

Forget the user's keys, then put the defaults back on the window's commands.

make_registry

make_registry() -> Registry

Return the session's registry, shared with the application's store.

Sharing the registry is what fills a command from the components the session built. An application given a store of another kind is left as it is.

open_span

open_span() -> AbstractContextManager[
    Callable[[str], None]
]

Open the span a QtHook.DURING_BUILD hook wraps the build in.

Without one, reporting stays where it was and nothing brackets the build. The runtime step has run by now, so the QApplication a hook is handed exists.

show

show() -> None

Show the window, giving its regions the sizes the layout declares unless a saved layout was restored.

The first show also grows the window, within the screen, to the size its views ask for. The sizes are given once, so showing the window again keeps what the user changed. run calls it; a script that runs the event loop itself calls it in place of showing main_window.

run

run() -> NoReturn

Build, show the window, and hand over to the event loop.

An exception no slot caught is logged with its traceback, and the window carries on.

Qt

Bases: Frontend

Qt frontend, attached by redsun.qt.attach.

check_view classmethod

check_view(view: type, where: str) -> None

Refuse a view whose constructor does not start (name: str, parent: QWidget.

The session passes both by keyword, so neither may sit after a /, and neither may sit after a *, so a missing parent shows in the first line of the signature.

Raises:

Type Description
TypeError

If the constructor starts any other way.

read_placement classmethod

read_placement(value: object) -> Placement

Return the Qt placement a session file's value names.

left, right, top or bottom is a dock against that edge, central the main area and status_bar a widget in the status bar; {dock: <edge>, group: <name>} a dock tabbed with its group, {menu: <name>} an entry in that menu and {toolbar: <name>} an entry in that toolbar.

Raises:

Type Description
ValueError

If value is none of these.

region_of classmethod

region_of(
    placement: Placement,
) -> tuple[str, str | None] | None

Return center for Central, a dock's edge and group, and None for a menu, toolbar or status bar item.

layout_problems classmethod

layout_problems(layout: WindowLayout) -> list[str]

Return what Qt cannot show of layout, a share for the centre and opposite edges filling the window included.

key_problems classmethod

key_problems(key: str) -> list[str]

Return why key is not one app-model reads, or nothing.

canonical_key classmethod

canonical_key(key: str) -> str

Return key as app-model writes it.

thread_of classmethod

thread_of(consumer: object) -> SlotThread

Run a widget's slots on the main thread, the only one it may be used from.

QtHook

Bases: StrEnum

The points a Qt session calls a hook at.

A member is its own string, so the attribute name declaring a hook, the key of a hooks configuration entry and a member here are the same thing said three ways.

CREATE_APPLICATION class-attribute instance-attribute

CREATE_APPLICATION = 'create_application'

Makes the QApplication from the command-line arguments, when none exists yet.

CONFIGURE_APPLICATION class-attribute instance-attribute

CONFIGURE_APPLICATION = 'configure_application'

Receives the QApplication before any view is made.

DURING_BUILD class-attribute instance-attribute

DURING_BUILD = 'during_build'

Receives the QApplication and wraps the build steps.

CONFIGURE_MAIN_VIEW class-attribute instance-attribute

CONFIGURE_MAIN_VIEW = 'configure_main_view'

Receives the main window once it is made, before it is shown.

CONFIRM_CLOSE class-attribute instance-attribute

CONFIRM_CLOSE = 'confirm_close'

Answers whether the window may close.

Placements

Dock dataclass

Dock(area: Area, group: str | None = None)

Bases: Placement

A panel against one edge of the window, tabbed with the docks of its group.

Raises:

Type Description
ValueError

If area names no edge of the window.

area instance-attribute

area: Area

Edge the panel sits against.

group class-attribute instance-attribute

group: str | None = None

Name of the docks it is tabbed with on the same edge; None for none.

Area module-attribute

Area: TypeAlias = Literal['left', 'right', 'top', 'bottom']

Central dataclass

Central()

Bases: Placement

The main area of the window, shared when more than one view asks.

MenuItem dataclass

MenuItem(menu: str)

Bases: Placement

An entry in a named menu of the menu bar.

menu instance-attribute

menu: str

Name of the menu.

ToolBarItem dataclass

ToolBarItem(toolbar: str)

Bases: Placement

An entry in a named toolbar.

toolbar instance-attribute

toolbar: str

Name of the toolbar.

StatusBarItem dataclass

StatusBarItem()

Bases: Placement

A widget kept at the right of the status bar, in declaration order.

The widget keeps the width its size hint gives it, so a view whose text changes length sets its own width.

attach

attach(
    window: QMainWindow,
    views: Mapping[str, AttachableComponent],
    placements: Mapping[str, Placement] | None = None,
    layout: WindowLayout | None = None,
    *,
    titles: Mapping[str, str] | None = None,
) -> None

Attach every view of views to window, where layout puts it or else where it asks.

placements gives, by name, the placement a view's declaration chose; any other view is placed where its placement asks. titles gives, by name, the text a dock or a central tab shows for a view; any other view shows its name. layout is a resolved layout, such as Session.resolve_layout returns; without one the placements alone decide, docks of one edge and group tabbed together in the order of views. Menu and toolbar items go where their placement asks.

Raises:

Type Description
TypeError

If a view asks for a placement Qt does not attach, or is not the toolkit type that placement demands.

ValueError

If layout leaves out a view that asks for a dock or the centre, or names one that is not in views.

Colour scheme

ColorSchemeMode

Bases: StrEnum

What a session asks the platform for, in the order the control cycles.

SYSTEM asks for nothing, which is Qt's unset state rather than a scheme of its own: the platform keeps deciding, and a user changing their own setting is followed.

SYSTEM class-attribute instance-attribute

SYSTEM = 'system'

The platform decides.

LIGHT class-attribute instance-attribute

LIGHT = 'light'

The light scheme.

DARK class-attribute instance-attribute

DARK = 'dark'

The dark scheme.

from_config classmethod

from_config(declared: str | None) -> Self

Return the mode the color_scheme key names, or SYSTEM for None.

Raises:

Type Description
ValueError

If the key names no mode the control offers.

apply

apply() -> None

Ask the platform for this scheme, or stop asking under SYSTEM.

Raises:

Type Description
RuntimeError

If no application exists yet to carry a colour scheme.

next

next() -> ColorSchemeMode

Return the mode after this one, wrapping past the last.

ColorSchemeButton

ColorSchemeButton(
    mode: ColorSchemeMode = ColorSchemeMode.SYSTEM,
    parent: QWidget | None = None,
)

Bases: QToolButton

Cycles the colour scheme, system to light to dark and back.

The icon is the mode asked for rather than the scheme in force, so it stays right while system follows a user changing their own setting.

Show mode, without applying it: the session already did.

TOOLBAR class-attribute

TOOLBAR: str = 'redsun.color-scheme'

Object name of the toolbar pin_to puts the control in.

mode property

mode: ColorSchemeMode

The mode asked for, which the icon shows.

pin_to classmethod

pin_to(window: QMainWindow, mode: ColorSchemeMode) -> Self

Return a control at the right of a toolbar of its own on window.

An expanding spacer takes the width before it, which is what pins the control to the right edge; nothing else goes in this toolbar, so a view asking for a toolbar keeps its own.

Raises:

Type Description
RuntimeError

If window refuses a toolbar.

cycle

cycle() -> None

Move to the next mode and ask the platform for it.

Styles

NapariStyle

NapariStyle(font_size: int | None = None)

Gives the window napari's look, dark or light as the colour scheme reads.

A configure_application hook provider. It applies napari's stylesheet and icons for the current colour scheme, then again at every change of the scheme, so the session's colour scheme control switches between napari's dark and light themes. An unknown scheme gets the light theme. Both themes' icons are written to the user's cache folder when the session builds. At shutdown the application gets back the stylesheet it had before.

Parameters:

Name Type Description Default
font_size int | None

The stylesheet's base font size in points; None keeps napari's own size for the platform.

None

Raises:

Type Description
ValueError

If font_size is not a positive whole number.

configure_application

configure_application(app: QApplication) -> None

Apply napari's theme for the current colour scheme, and again on each change.

shutdown

shutdown() -> None

Stop following the colour scheme, and restore the previous stylesheet.

QlementineStyle

QlementineStyle(
    dark: str | PathLike[str] | None = None,
    light: str | PathLike[str] | None = None,
    animations: bool = True,
)

Gives the window qlementine's look, dark or light as the colour scheme reads.

A configure_application hook provider. It sets qlementine's style on the application, in its dark or light theme for the current colour scheme, then changes theme at every change of the scheme, so the session's colour scheme control switches between the two. An unknown scheme gets the light theme.

qlementine sets the application's font and palette as well. It also draws every icon in the window in one colour, that of the control the icon is on, so an icon whose colours carry a meaning loses them. At shutdown the application gets back the style, the font and the palette it had before; a style that has no name cannot be put back, and stays replaced.

qlementine's package is imported when the hook runs, so only a session that names this style needs it. The theme files are read then too.

Parameters:

Name Type Description Default
dark str | PathLike[str] | None

A qlementine theme file used while the colour scheme is dark, in place of qlementine's dark theme. A relative path is read from the working directory.

None
light str | PathLike[str] | None

The same, for the light scheme.

None
animations bool

Whether qlementine animates a control changing state.

True

Raises:

Type Description
TypeError

If a theme is neither a path nor None, or animations is not a bool.

configure_application

configure_application(app: QApplication) -> None

Set qlementine's style on app, in the theme of the current colour scheme.

A failure leaves the application as it was.

Raises:

Type Description
ImportError

If qlementine's package for the Qt binding in use cannot be imported.

ValueError

If a theme file cannot be read.

shutdown

shutdown() -> None

Stop following the colour scheme, and restore the previous style, font and palette.

Actions

ActionError

Bases: RuntimeError

An actions configuration entry cannot be turned into an action.

SAVE_MENU module-attribute

SAVE_MENU: Final[str] = 'redsun/file'

The menu a session's own actions join, which a window may show by name.

WINDOW_MENU module-attribute

WINDOW_MENU: Final[str] = 'redsun/window'

The menu holding a toggle for each dock and "Reset layout", shown by the session's window.

The session adds it at the end of the menu bar unless the bar already shows it.

ASK_ON_CLOSE module-attribute

ASK_ON_CLOSE: Final[str] = 'ask_on_close'

The settings key holding whether the close prompt still appears.