Skip to content

Widgets

Subclass the FXMainWindow

You can subclass any widgets in the fxwidgets module. Here's a practical example with FXMainWindow:

# Third-party
from qtpy.QtWidgets import QWidget, QVBoxLayout, QPushButton

# Internal
from fxgui import fxwidgets, fxicons


class MyWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.add_layout()
        self.add_buttons()

    def add_layout(self):
        """Adds a vertical layout to the main layout of the widget."""

        self.main_layout = QVBoxLayout()
        self.setLayout(self.main_layout)

    def add_buttons(self):
        """Adds buttons to the main layout of the widget."""

        # Use fxicons for theme-aware icons
        home_button = QPushButton("Home")
        fxicons.set_icon(home_button, "house")

        settings_button = QPushButton("Settings")
        fxicons.set_icon(settings_button, "settings")

        self.main_layout.addWidget(home_button)
        self.main_layout.addWidget(settings_button)
        self.main_layout.addStretch()


class MyWindow(fxwidgets.FXMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setCentralWidget(MyWidget(parent=self))
        self.adjustSize()


application = fxwidgets.FXApplication()
window = MyWindow()
window.setWindowTitle("Subclassed FXMainWindow")
window.show()
application.exec()
python -m fxgui.examples

A window opens with every public widget, a page per kind: buttons, inputs, display, containers, lists and trees, the timeline, windows and dialogs, and docking. Each box is titled with the class names it shows. Window > Theme switches the theme, so you can see a widget in each. The Docking page needs PySide6-QtAds (see Installation).

Available Widgets

The fxwidgets module holds these classes:

Class What it is
FXAccordion Collapsible sections stacked; one open at a time unless exclusive=False
FXApplication The QApplication that themes every window it owns
FXAvatar Round avatar: a photo, or initials on a disc coloured by the name
FXBreadcrumb Clickable breadcrumb trail; double-click it to type a path. Its parts are parted by a 14 px chevron in text_dimmed (separator="/" for a slash). back_button and forward_button name its navigation buttons (None without show_navigation)
FXCamelCaseValidator Accepts camelCase letters only
FXCapitalizedLetterValidator Accepts a name starting with a capital letter
FXCheckableComboBox Combo box whose popup stays open while several rows are ticked
FXCodeBlock Read-only code with syntax highlighting
FXCollapsibleWidget A titled section that opens and shuts its content
FXCommand One row of an FXCommandPalette: a label, a callable or a list of choices, keys, the section it is grouped under
FXCommandPalette Popup search over a window's commands, grouped by section, or over rows to go to; the commands run lately come first
FXCommandRow A toolbar fixed in place, whose margins survive style changes
FXConfirmDialog The same card for any confirm: verb, tone="plain" (a primary verb) or "danger" (red), an optional alternative (with alternative_tone) at the left, and default (the choice Enter takes: the verb when plain, Cancel when danger). exec() returns VERB, CANCEL or ALTERNATIVE; choice() names it. Escape cancels. The card has no title bar: drag it by its title. Given a parent (a DCC's main window included), it is owned by that window and stays above it
FXInputDialog The confirm card asking for one value: kind="line", "text" (Ctrl+Enter takes the verb) or "choice" (from choices), a starting value, a placeholder, and required to keep the verb shut while the field is empty. field is the input; value() reads it
FXConfirmDeleteDialog Asks before an act with no undo: a card with the question, Cancel then a red Delete, focus on Cancel; Enter never deletes, and the window behind dims. require_typing=True (on when a confirm_word is given) waits for the name typed exactly
FXDropZone Drop target for files or folders, with a browse button and a file list
FXElidedLabel Label that cuts its text with "..." when it does not fit
FXEmojiButton Round icon button that opens an FXEmojiPicker and can insert into an editor
FXEmojiPicker Popup grid of emoji, keyboard navigable
FXEmptyState What a pane shows before it has content: an icon, the action to take in bold, what it brings muted (see Empty Panes)
FXFilePathWidget File or folder path field with a browse button
FXFilteredTree An FXKeyboardTree under a filter bar, with expand-all and collapse-all; actions= puts a row of buttons under the tree
FXFloatingDialog Dialog that opens at the pointer
FXFlowLayout Layout that wraps its widgets onto new lines, like words
FXIconButton Round icon button; checkable, filled with the accent when checked
FXIconLabel Label that draws an icon in the theme's colours at paint time
FXIconLineEdit Line edit with an icon on the left or right
FXJoinedGroup Widgets side by side in one pill outline, such as a status and a Post button
FXKeyboardTree Tree whose row menus, Enter and typing work from the keyboard
FXKeycap A shortcut drawn as keys, one cap per key, round at the button radius; follows every theme switch
FXLettersUnderscoreValidator Accepts letters and underscores, numbers optional
FXLoadingOverlay Spinner over a widget, dimming it and blocking its input
FXLoadingSpinner Animated loading indicator: spinner, dots or pulse
FXLowerCaseValidator Accepts lowercase letters, numbers and underscores optional
FXMainWindow Main window with menus, toolbar, status bar and a theme menu
FXMentionEdit Text box that offers people by name after an @ and lists who it names
FXNotificationBanner Card with a message that slides in from a window's right edge. severity(), timeout(), action_buttons() and is_placed() (it stands at its slot, no slide running) read it back
FXMeterBar A quiet meter: one fill or several coloured shares (FXMeterShare(value, color, faint)), 6 px or 4 px compact
FXOutputLogHandler Logging handler that writes records into an FXOutputLogWidget
FXOutputLogWidget Read-only log display with search. It writes queued records on a throttle; flush() writes them all now
FXPasswordLineEdit Password field with a show/hide eye icon
FXPrimaryButton The main action of a form, on the theme's accent
FXProgressCard Card showing a task's progress and status
FXPygmentsHighlighter Pygments syntax highlighter for any QTextDocument
FXRangeSlider Slider with two handles for a low and a high value
FXRatingWidget Star rating input, halves optional
FXResizedScrollArea Scroll area whose height follows its content, between a floor and a cap
FXScrollShadow A line and a fade where a scroll area cuts its content off below; gone at the end
FXSearchBar Search field with a clear button and a debounced search signal
FXSeating Seats a tray panel in the screen corner nearest its icon and slides it in
FXSingleInstance Lock on a local socket name; a second start wakes the first
FXSingleton Metaclass for Qt classes that have one instance
FXSkeleton Grey blocks in the shape of a list, cards, text or a grid (a name column, then columns narrow ones) while they load, a light sweeping across (see Loading)
FXSortedTreeWidgetItem Tree row that sorts numbers in text naturally (v2 before v10)
FXSplashScreen Splash screen with a title, a text and a progress bar
FXSplitButton Split button whose click and dropdown both have keys
FXStatusBar Status bar with an accent line, messages, items and a busy line
FXStatusDot Small clickable circle in a feedback colour, grey for no state
FXStatusItem Icon and word on a status bar, lit when clickable
FXSummaryRow Totals row pinned under a tree or table view, lined up with its columns (see Summary Rows)
FXViewFooter A row of actions at the foot of a tree's or table's card, under its rows and summary (see Card Footers)
FXSystemTray System tray icon with a menu
FXTagChip One tag, removable or not: a neutral hairline chip; color= adds an 8 px dot (a token name or a colour)
FXTagInput Field that turns what you type into FXTagChips
FXThreadLine Line over a comment thread, from the comment's face into each reply's
FXThumbnailDelegate Item delegate with thumbnails, status dots, labels and stars. The child count follows a row's name; GROUP_ROW_ROLE draws a group header row (12 px, emphasised, toned); an item's own Qt.FontRole weight sets its title's; Qt.TextAlignmentRole aligns a cell; align_column(view, column, alignment, tabular) aligns a column and its header, TABULAR_FIGURES_ROLE or tabular=True lines its digits up; THUMBNAIL_SIZES gives the picture per row height (32 x 18, 44 x 24, 72 x 40)
FXTimelineSlider Timeline with playback, keyframes, markers and a loop region. show_track=False hides the track; marker_frames(name), region(name) and tick_positions(width, first, last) read back what it draws, and mark_in_button, mark_out_button, go_to_start_button, go_to_end_button and frame_field name its widgets
FXToggleSwitch On/off switch that slides: a dimmed grey track off, the accent on, a page-coloured knob
FXTopProgress A 2 px accent line along a widget's top edge while it works (see Loading)
FXValidatedLineEdit Line edit that shakes and flashes when its validator refuses a key

fxdocking.FXDockArea docks named panes around a body; it needs PySide6-QtAds (see Installation). show_dock(name), hide_dock(name) and is_dock_open(name) open, close and ask about a pane by its name, without reaching for QtAds. show_dock(name, activate=False) makes a pane its tabs' current one without raising or focusing the floating window it sits in.

A pane's content stands fxstyle.PANE_GAP off its sides and bottom, but a flush list, tree or table (fxstyle.mark_flush) runs to the pane's border, as a table sits in a card: its header, rows, selection, column rules and FXSummaryRow with it, the vertical scroll bar at the border. It reaches the bottom when nothing stands under it. A filter bar, a form, buttons under the list and a log keep the gap; an FXFilteredTree's tree runs to the border while its filter bar keeps the gap. A pane whose body is a list, tree or table is flush already, and so is a view marked flush after it was docked. The pane's bottom corners stay round over the rows.

And these functions and constants:

Name What it does
align_labels Gives the labels of several forms one right-aligned column
apply_tip Sets a rich tooltip and a plain status tip on a widget, an action or a view's item (see Tooltips)
fix_wrapped_heights Gives every word-wrapped label under a widget the height its width needs
grab_screen_region Lets the user drag out a screen region and returns it, or None on Escape
keycap Renders a shortcut as keys in a tooltip's HTML; on a window, use FXKeycap
tip Returns the HTML apply_tip shows, in the theme in force
DEFAULT_EMOJIS The emoji an FXEmojiPicker offers by default
CRITICAL, ERROR, WARNING, SUCCESS, INFO, DEBUG Severities for messages, banners and progress cards

Tip

Every widget follows a theme switch with no call of its own.

from fxgui.fxwidgets import FXBreadcrumb

crumb = FXBreadcrumb(home_icon="", tab_stops=False)
crumb.set_path(["pilot", "sq010", "sh0040", "comp"])
crumb.set_edit_placeholder("Type a shot")
  • Every segment but the last is a button: it tints under the pointer and shows a pointing hand. The last one is where the path already is, so it is bold and does nothing.
  • The strip behind the segments is a filled field, brighter while the pointer is over it. Double-click it to type a path; a press anywhere outside closes the editor, and so does exit_edit_mode().
  • The colours are worked out each time the strip paints, from the theme and from what the breadcrumb sits on: the frame colour on a framed window's toolbar or a band marked with mark_as_frame, the surface anywhere else. The text reads at 4.5:1 on both fills and the edge shows at 1.3:1 against the ground and both fills, in every bundled theme. A theme switch needs no call.
  • tab_stops=False takes the segments and the back and forward buttons out of the Tab order. The path editor keeps its stop.

The starting colours are class attributes, so a subclass names its own tokens:

from fxgui.fxwidgets import FXBreadcrumb


class HouseCrumb(FXBreadcrumb):
    STRIP_RESTING_TOKEN = "surface_alt"
    SEGMENT_HOVER_TOKEN = "text_muted"
    SEGMENT_HOVER_ALPHA = 48

Do not point STRIP_RESTING_TOKEN at surface: in every bundled theme that is the window's own colour, so on a plain window the strip disappears.

A breadcrumb can show words of its own over the raw path parts. Pass segment_labels=, a function from the parts to one word per part, or override segment_labels(self, path) in a subclass:

from fxgui.fxwidgets import FXBreadcrumb

crumb = FXBreadcrumb(
    home_icon="",
    segment_labels=lambda parts: [p.replace("sq", "Sequence ") for p in parts],
)
crumb.set_path(["pilot", "sq010"])  # shows "pilot / Sequence 010"

path(), the editor and every signal keep the parts. A list of the wrong length shows the parts.

Your Own Item-Data Roles

FXThumbnailDelegate reads item-data roles of its own off the items it paints, from Qt.UserRole + 1 up to FIRST_FREE_ROLE, and FXSortedTreeWidgetItem.SORT_ROLE sits in the same range. A view that puts roles of its own on the same items derives them from FIRST_FREE_ROLE:

from fxgui.fxwidgets import FXThumbnailDelegate

ROW_KIND_ROLE = FXThumbnailDelegate.FIRST_FREE_ROLE
ROW_COLOR_ROLE = FXThumbnailDelegate.FIRST_FREE_ROLE + 1

Warning

Do not guess a number instead. Every number below FIRST_FREE_ROLE is one the delegate reads: a view storing its own value on CHILD_COUNT_VISIBLE_ROLE's number gets a child count drawn on rows with no children.

A role added to the delegate moves FIRST_FREE_ROLE up, and every role derived from it moves too.

Keyboard Trees

FXKeyboardTree.type_into(field) sends what is typed on the tree to a filter field, and FXFilteredTree does it for you. So a tree needs no "focus the filter" shortcut: start typing.

from fxgui.fxwidgets import FXFilteredTree

tree = FXFilteredTree(placeholder="Filter shots...")
# Typing on tree.tree goes to tree.filter_bar.

Ctrl, Alt and Meta chords stay commands. A character typed with AltGr is typing, even though Windows reports AltGr as Ctrl+Alt.

Note

A shortcut made of one symbol (/, ?) depends on the keyboard layout. Qt matches the character typed, not the key's position, so on AZERTY / is Shift+:. A window shortcut of one character also wins over typing on the tree. So keep single-character shortcuts off windows that hold a filtered tree, or use a chord such as Ctrl+F.

Summary Rows

FXSummaryRow pins one row of totals under a QTreeView or a QTableView, such as "9 shots | 5/63 tasks done | 300 | 0.1 d". You count the totals; the row shows the text you hand it.

from qtpy.QtCore import Qt
from fxgui.fxwidgets import FXSummaryRow

summary = FXSummaryRow(view)
summary.set_texts(["9 shots", "5/63 tasks done", "300"])
summary.set_text(3, "0.1 d", Qt.AlignRight, strong=True)
# Recount and call set_text or set_texts again when the rows change.
  • It is not a model row. It sits in the view's bottom margin, so it stays in place while the rows scroll. It is never selected and never takes focus.
  • Each cell stays over its column when a column is resized, hidden, moved or scrolled sideways.
  • A cell takes its own alignment, else the column header's alignment (headerData with Qt.TextAlignmentRole), else the left.
  • The text is a step below the body and muted. strong=True draws it in the body colour.
  • It is as tall as a row at the current row size (36 px at "normal") and follows fxstyle.apply_row_size.
  • text(column) reads a cell back, clear() empties every cell, and setVisible(False) hides the row and gives its room back to the rows.
  • Screen readers read it as "Summary", and each cell as static text.

Card Footers

FXViewFooter puts a row of actions, such as Add and Remove, at the foot of a tree's or table's card: under its rows and any FXSummaryRow, inside the card's edge, on the card's surface with a rule above.

from qtpy.QtWidgets import QHBoxLayout, QPushButton
from fxgui.fxwidgets import FXViewFooter

actions = QHBoxLayout()
actions.addWidget(QPushButton("Add"))
actions.addWidget(QPushButton("Remove"))
actions.addStretch()
FXViewFooter(table, actions)
  • The scroll bars scroll the rows and the summary, so they end above the footer: the horizontal one runs right under the summary.
  • setVisible(False) hides the footer and gives its room back.
  • FXFilteredTree(actions=...) makes one, kept as its footer.
  • A view with no frame of its own (fxstyle.mark_flush, a dock pane's body) draws a rule along its header's top, as the card's edge does on a framed one, whatever sits above it.

Empty Panes

A pane with nothing to show yet says what to do next. FXEmptyState centres an icon, the action in bold and, under it, what that action brings, in the muted ink:

from fxgui.fxwidgets import FXEmptyState

empty = FXEmptyState("inbox", "Pick a task", "Its files and versions show here")
empty.set_prompt("search", "Search again", "Nothing matched")
action, detail = empty.prompt()

An empty detail hides the second line. A disabled empty state keeps its icon muted, so a pane switched off still reads its ask.

FXScrollShadow(area) draws a line and a fade over the bottom of a scroll area's viewport, where it cuts its content off, and hides once the area is scrolled to the end or has nothing to scroll. It reads the theme's shadow and border each time it paints.

Loading

A list or a pane waiting for its data shows its own shape, greyed, rather than an empty page or a spinner. FXSkeleton draws rows (a row's height, a thumbnail slot and text bars), cards or lines of text, in a grey a touch off the ground, with one light sweeping across every 1.6 s:

from fxgui.fxwidgets import FXSkeleton, FXTopProgress

FXSkeleton.cover(tree)            # Over the rows; the header stays.
...                               # The data arrives.
FXSkeleton.uncover(tree)

cards = FXSkeleton(kind="cards", count=6)   # Or "rows", "lines", "grid".

cover puts the skeleton inside a list's, tree's or table's frame and keeps it the view's size; count=None fills the height.

FXTopProgress(widget) runs a 2 px accent line along the widget's top edge, over its content, letting the mouse through. start() shows a wait of unknown length: past 150 ms the line creeps toward 90 % until finish() runs it to the end and fades it. set_value(0.4) shows a known share instead.

Screen readers hear "Loading" from both; the line is a progress bar with its value. Under reduced motion (FXGUI_REDUCED_MOTION=1) the skeleton's light stays still, a wait is a still, full line, and finish() hides it at once.

Segmented Tabs and Tab Counts

A view switch (Table | Gantt | Board) is a tab bar marked segmented: the tabs sit side by side on a track, and the picked one is a raised chip that slides to the tab you pick. It stays a QTabBar, so its signals, keyboard and currentIndex are Qt's own. Mark a bar or a whole QTabWidget:

from qtpy.QtWidgets import QTabBar
from fxgui import fxstyle

views = QTabBar()
for name in ("Table", "Gantt", "Board"):
    views.addTab(name)
fxstyle.mark_as_segmented(views)
views.currentChanged.connect(show_view)

fxstyle.mark_as_segmented(views, False) gives the plain tab look back.

A count after a tab's label works on any fxgui tab bar, segmented or plain. Pass None to remove it. A screen reader reads the tab as "Pipeline, 5".

fxstyle.set_tab_count(views, 0, 26)
fxstyle.set_tab_count(views, 0, None)

On a closable bar whose close buttons stand on the right, the count stands before the label. Set the count again after renaming a tab, so the name a reader hears follows. The gallery's Containers page shows both.

Tab Order

fxutils.set_tab_order(widgets) chains widgets into exactly the order given; Shift+Tab walks it back. A compound widget whose focus a proxy takes (an inner line edit) chains through that proxy, which a bare QWidget.setTabOrder would not move.

from fxgui import fxutils

fxutils.set_tab_order([name_edit, path_widget, ok_button])

Tooltips

apply_tip is fxgui's tooltip. It hands Qt's own setToolTip a small HTML string, and sets a markup-free status tip for the window's status bar:

from qtpy.QtWidgets import QPushButton
from fxgui.fxwidgets import apply_tip

save_button = QPushButton("Save")
apply_tip(
    save_button,
    "Save",
    "Write the current scene to disk, overwriting the last version",
    "Ctrl+S",
)

The title is in the theme's primary text, the body dimmed, and the shortcut follows the title after a middle dot, as keycaps, one per key: Ctrl S. The keys of one chord sit close; a second chord (Ctrl+K, Ctrl+S) sits further away. Key names come from QKeySequence, so a Mac shows its own glyphs rather than the word "Ctrl".

Target What happens
A widget The tip is rebuilt each time it is about to show
A QAction The tip is rebuilt when the action is hovered, before its tool button or menu shows it
An item of a QListWidget, QTreeWidget or QTableWidget The view builds the tip when it shows; a tree item gets it on every column. Add the item to its view first, or apply_tip raises ValueError

A tip about a thing, such as a file or a version, takes three more parts, all by name:

apply_tip(
    item,
    "livetest v001",
    facts=[("Product", "render/livetest"), ("Files", "8 x .exr"), ("Status", status)],
    code=path,
    hint="Double-click to play the preview",
)
Part What it shows
facts (label, value) pairs as a table, in the order given: the label dimmed, the value in the primary text. A pair whose value is empty or None is left out
code A path, a key or a command, in the theme's mono face on a faint fill. A line longer than 64 characters is cut into rows after a folder separator, so a long path never widens the tooltip
hint A closing line, dimmed: what a double-click does

The blocks come in that order under the title and body, with a little air between them. The accessible description carries the same words, one part per line, without markup.

The HTML holds the colours of the theme in force, so rebuilding at show time is what makes a tip set in one theme show in the next. Every string is HTML-escaped, so a path holding & or < reaches the user as text, and a newline in the body breaks the line. Qt's rich text draws no rounded background, so a keycap in a tooltip is square.

Two lower-level helpers:

  • tip() returns the HTML. Call it when the tip shows: a model returns tip(...) from data() for Qt.ToolTipRole, which Qt asks for on hover.
  • keycap() returns a shortcut's keycaps as HTML. A label reads its text once, so a keycap on a window is an FXKeycap instead: a widget, one cap per key, round at the button radius, that follows every theme switch.