Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
Numeric editors

Русская версия · LineEdit · Sliders

Choose SpinBox for a bounded finite number that users can type or adjust by steps; a Slider instead emphasizes position in a range. The SpinBox API and numeric source document checked values and range constraints. The application below demonstrates the available appearances.

Use ui::spinBox() to edit a finite number as text or with step buttons. The default value is zero, the inclusive range is 0..100, the increment is one, and the publication mode is EditMode::IMMEDIATE.

A complete application

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_style.hpp>
#include <format>
int main() {
using namespace portals;
ui::Ref<SpinBox> quantity, priority, discount;
// clang-format off
return ui::scene(
ui::vbox(
ui::label("Order settings | type a value or use the step buttons"),
ui::vbox(
ui::hbox(ui::label("Quantity (standard)").width(24),
ui::spinBox(quantity, 25).range(0, 100).skin("standard").width(22)),
ui::hbox(ui::label("Priority (compact)").width(24),
ui::spinBox(priority, 2).range(0, 5).skin("compact").width(22)),
ui::hbox(ui::label("Discount (arrows)").width(24),
ui::spinBox(discount, 10).range(0, 50).skin("arrows").width(22)))
.framed("rounded", "Order"),
ui::vbox(
ui::hbox(ui::label("Shipping (read-only)").width(24),
ui::spinBox(3).skin("standard").width(22).readOnly()),
ui::hbox(ui::label("Reserved (unavailable)").width(24),
ui::spinBox(12).skin("arrows").width(22).enabled(false)))
.framed("rounded", "Availability"),
ui::hbox(
ui::button("Reset", [=] {
quantity.value() = 25;
priority.value() = 2;
discount.value() = 10;
status.text() = "Defaults restored";
}),
ui::button("Themes", [themes] { return themes.open(); })),
ui::label(status, "Adjust an order value."),
ui::label("Tab: focus | Up/Down: adjust | F10: quit"))
.maxWidth(64),
ui::themeSelector(themes, {
{"nord", "Nord", nordTheme},
{"latte", "Latte", catppuccinLatteTheme}}))
| ui::theme(nordTheme())
| ui::onChange(quantity, [status](double value) {
status.text() = std::format("Quantity: {:.0f}", value);
})
| ui::onChange(priority, [status](double value) {
status.text() = std::format("Priority: {:.0f}", value);
})
| ui::onChange(discount, [status](double value) {
status.text() = std::format("Discount: {:.0f}%", value);
})
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
TextProperty text(TextResolver resolver={}, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1968
std::expected< RadioGroupValue, ManagedError > value() const
Definition ui_ref.hpp:782
std::expected< void, ManagedError > open(std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1013
Public Portals API.
Definition action.hpp:8
StyleSheet nordTheme()
StyleSheet catppuccinLatteTheme()

The complete source shows three skins, read-only and disabled fields, reset, and a Nord/Latte theme selector. Build it with cmake --build <build> --target portals_docs_spin_box. For an installed SDK, use the same source with Package setup. The numeric form example explores deferred publication and shared numeric behavior; its target is portals_numeric_form. Both programs use ui::runApp() for terminal restoration and scene cleanup.

Skins and structure

Select an appearance with .skin("standard"), .skin("compact"), or .skin("arrows"). The typed values are SpinBoxSkin::STANDARD, SpinBoxSkin::COMPACT, and SpinBoxSkin::ARROWS. The native constructor accepts SpinBox(SizePolicy = DEFAULT_CONTENT_POLICY, SpinBoxSkin = SpinBoxSkin::STANDARD). A skin is fixed at mount time; remount the control to change it.

Each skin has an eight-cell preferred editor. Standard (the default) has two five-cell bracketed buttons, [ - ] and [ + ]; compact retains one-cell - and + buttons for a ten-cell intrinsic width. Arrows uses [ ▼ ] and [ ▲ ]; when the active WidthPolicy does not give the arrows one cell, it uses v and ^ instead. These are intrinsic sizes; layout constraints may allocate more space. All skins have exactly three children: a LineEdit and two buttons. Tab visits only the editor; the buttons are not focus stops. The numeric model and validation are the same for every skin. The editor retains its selection, Unicode text limits, clipboard policy and Undo/Redo history.

Draft and numeric source

ManagedScene::remove rejects removal of a bound SpinBox's editor or either step button with INVALID_ARGUMENT; remove the whole SpinBox instead. Removing an individual structural child directly through WidgetTree while its binding is active bypasses this managed ownership contract.

Numbers use locale-independent decimal syntax, a dot and an optional exponent. The complete draft must represent a finite number within the configured bounds. An empty draft, a sign, an unfinished exponent, invalid text or an out-of-range number remains visible without publishing to the numeric source. Successful confirmation preserves accepted spelling such as 01 or 1e0 until a real external change. A custom locale or precision formatter is not supported.

Mode Publication
IMMEDIATE Each valid accepted change
ON_COMPLETION Enter or focus loss
EXPLICIT Enter; focus loss keeps the draft

Escape adopts the latest source and resets the baseline. Own confirmation keeps history. An external change updates a clean field; a dirty field keeps its draft and reports a revision conflict at confirmation. Changing bounds or increment is also an external revision, even when the numeric value is unchanged.

amount.text() and amount.lineEdit().text() access the same visible draft. amount.value() = 3.5 follows the selected edit mode. amount.value().get() reads the valid visible numeric draft; incomplete syntax returns NumericError::INVALID_TEXT, nonfinite input returns NOT_FINITE, and out-of-range input returns OUT_OF_RANGE. The getters do not discard text or automatically report errors.

An assignment returns an independent observation:

// amount is a mounted ui::Ref<SpinBox> in EXPLICIT mode.
auto assignment = amount.value() = 3.5;
auto observed = assignment.result();
// On success, observed->editing describes draft acceptance.
// observed->commit is present only when a numeric publication actually occurred.

Share a model and observe changes

Create ManagedScene::numericState(initial, NumericRange) in a scene factory and pass it to ui::spinBox(reference, model). The same NumericState works with a Slider. Its snapshot() reads the committed numeric value even while the editor shows a different draft. set(double) writes directly to the source; configure(initial, range) replaces the value and complete range atomically. Explicit value/range/step overrides on a recipe using an external model are an INITIAL_CONFLICT, including equal overrides. Invalid numeric configuration retains its original NumericError and leaves the source unchanged.

ui::onChange(amount, callback) receives a double or the exact PropertyUpdate<NumericValue> for a changed user publication. External and fluent writes and equal publications do not invoke it. Text editing and completion observations remain available through the LineEdit reference. Receipts own their original snapshots even when a callback writes again or removes the control.

Input, resources and styling

Up/Down and the two buttons step by .step(value). PageUp/PageDown apply .pageSteps(count) increments, ten by default. A valid dirty draft is the starting point; an invalid draft is preserved. A clean field steps from the complete source value, including an off-grid fraction. Steps saturate at the bounds and follow the current edit mode. Each step is a separate ordinary history operation.

.readOnly() blocks user input, history mutation and steps; it makes the control read-only rather than disabled. Programmatic text, numeric draft and external model writes remain available. Disabled ancestry also blocks user mutation.

The registered SpinBox resource accepts numeric value, minimum, maximum, step, pageSteps, readOnly, editMode, skin, ordinary text/history/limits and sizing/frame properties. Sparse settings preserve absent factory leaves; explicit false settings remain overrides. Numeric failures preserve the causal property origin. SpinBox is the natural root style type. Its real children use LineEdit and Button with classes spin-box-editor, spin-box-decrease and spin-box-increase; both buttons also have spin-box-button. Ordinary theme, class and ID rules apply. For example, SpinBox{skin="arrows", value=10} selects the arrows skin in a resource.

Styling reference

SpinBox is a layout root, not the painted editor. Its children are a LineEdit and two Button widgets. Target the confirmed classes .spin-box-editor, .spin-box-button, .spin-box-decrease, and .spin-box-increase. The skin determines button captions; PSS has no glyph property for changing them. The editor paints normal/focused/disabled, selected and caret as described in LineEdit; buttons paint normal/focused/disabled. Editor manual defaults come from LineEditOptions, buttons use ControlStyle{}. Style the children independently; a root declaration does not propagate to them.

The common paint properties apply to each painted target:

Property Value
foreground #RRGGBB text/ink color
background #RRGGBB fill color
bold true or false
italic true or false
underline true or false

Manual ControlStyle defaults use terminal colors, normal text, bold focus and italic disabled text. Theme and PSS declarations override individual manual fields; unspecified fields retain lower-layer values, including explicit false. A selector without a state supplies all variants. See cascade and selectors and styles.

Layout properties width and height accept nonnegative cell counts, auto, fit-content, or flex(positive weight); min-width, max-width, min-height, and max-height accept nonnegative cell counts. They require selectors without state or :read-only; Except for min-width, these size declarations are runtime PSS only. Conflicting widget bounds reject the update and retain the previous style and geometry; constraints and recipe precedence are explained in layout. These affect allocation, not the glyphs themselves.

.spin-box-editor { min-width: 8; }
.spin-box-editor:focused { background: #245070; }
.spin-box-button { foreground: #62b4d7; }