Callbacks#
Widgets tell your app what the user did through callbacks: functions you
hand to a widget's on_... setter. A button calls on_click when it is
clicked; a slider calls on_change with its new value; a list calls
on_select with the row index. This page shows how to connect them, when
they run, and what each one receives.
Connecting a callback#
auto& root = ctx.set_root<slikui::Column>();
root.set_padding(16).set_gap(8);
auto& count = root.add<slikui::Label>("Clicked 0 times");
int clicks = 0;
root.add<slikui::Button>("Click me").on_click([&] {
++clicks;
count.set_text("Clicked " + std::to_string(clicks) + " times");
});
auto& volume = root.add<slikui::Label>("Volume 50");
root.add<slikui::Slider>()
.set_range(0, 100)
.set_value(50) // setters don't run the callback
.on_change([&](float v) {
volume.set_text("Volume " + std::to_string(int(v)));
});
root.add<slikui::TextField>()
.set_placeholder("Name, then Enter")
.on_submit([&](std::string_view name) {
count.set_text("Hello, " + std::string(name));
});
root = ui.set_root(slikui.Column, padding=16, gap=8)
count = root.add(slikui.Label, "Clicked 0 times")
state = {"clicks": 0} # app state the callbacks share
def on_click():
state["clicks"] += 1
count.set_text(f"Clicked {state['clicks']} times")
root.add(slikui.Button, "Click me", on_click=on_click)
volume = root.add(slikui.Label, "Volume 50")
root.add(slikui.Slider, range=(0, 100), value=50,
on_change=lambda v: volume.set_text(f"Volume {int(v)}"))
root.add(slikui.TextField, placeholder="Name, then Enter",
on_submit=lambda name: count.set_text(f"Hello, {name}"))
The pattern is the same for every widget:
on_xxx(fn)storesfnand returns the widget, so it chains with the other setters. Each slot holds one callback; callingon_xxxagain replaces it.- Python: pass any callable, either through the setter
(
slider.on_change(fn)) or as a keyword when building the widget (root.add(slikui.Button, "OK", on_click=fn)). - Arguments: the callback receives the new value, or the index of the
row or item that was picked. The table below lists
them. Python gets plain types:
float,bool,intfor indices,strfor text, plusslikui.Colorandslikui.Vec2.
When callbacks run#
- Inside
ctx.handle(event), synchronously, on the UI thread, while the event that caused them is being dispatched. Nothing is queued. (A setter that fires its callback, and closing a menu or dialog from your own code, call them from that call instead.) - After the widget has updated itself. In
on_change,slider.value()already returns the new value; inon_select,list.selected()is the new row. - Only for changes the user makes, unless you ask. Every setter for a
value that a callback reports takes a last
fire_callbackargument, defaultfalse:slider.set_value(0.5)moves the slider silently, so updating a widget from your own state never loops back into your callback. Passtrueto run the callback as if the user had made the change:slider.set_value(0.5, true). Either way the callback only runs if the value actually changed. The last column of the table names each widget's setter. - The tree may be changed from inside a callback. You can add widgets,
remove widgets (even the one whose callback is running), open or close
dialogs and popups, and move focus. Removed widgets are destroyed when
the current
handle()returns, not mid-dispatch. - Buttons fire on release: a press and release on the same widget, Enter or Space. Dragging off the button before releasing cancels the click.
Every callback#
"Setter" is the widget's own setter for the same value. It runs the
callback only when given fire_callback = true and the value changes.
| Widget | Callback | C++ signature | Python receives | Fires when | Setter |
|---|---|---|---|---|---|
Button, IconButton |
on_click |
void() |
nothing | clicked, or Enter/Space when focused | - |
Checkbox, Radio, Switch |
on_change |
void(bool checked) |
bool |
toggled by click or Space (Switch: also Enter) | set_checked |
Slider |
on_change |
void(float value) |
float |
dragged, or keys | set_value |
DragValue |
on_change |
void(float value) |
float |
dragged, typed, or keys | set_value |
Vec2Edit / Vec3Edit / Vec4Edit |
on_change |
void() |
nothing: read the bound array | any component changed | - |
Vec2Pad |
on_change |
void(Vec2 value) |
slikui.Vec2 |
dragged, or arrow keys | set_value |
ColorEdit |
on_change |
void(Color color) |
slikui.Color |
edited in the picker | set_color |
Segmented |
on_select |
void(size_t index) |
int |
a segment picked | set_selected |
Tabs |
on_change |
void(size_t index) |
int |
a tab picked | set_selected |
TextField, SearchBox |
on_change |
void(std::string_view text) |
str |
every edit | set_text |
TextField, SearchBox |
on_submit |
void(std::string_view text) |
str |
Enter pressed | - |
TextArea |
on_change |
void(std::string_view text) |
str |
every edit | set_text |
ListView |
on_select |
void(size_t index) |
int |
a row clicked, or moved to with keys | set_selected |
ListView |
on_activate |
void(size_t index) |
int |
double-click, or Enter/Space | - |
Dropdown |
on_select |
void(size_t index) |
int |
an item chosen | set_selected |
TreeView |
on_select |
void(size_t row) |
int |
a row clicked, or moved to with keys | set_selected |
TreeView |
on_toggle |
void(size_t row, bool open) |
int, bool |
a row opened or closed by its arrow or Left/Right | set_expanded(row, open) |
TreeView |
on_activate |
void(size_t row) |
int |
double-click, or Enter/Space | - |
Table |
on_select |
void(size_t row) |
int |
a row clicked, or moved to with keys | set_selected |
Table |
on_activate |
void(size_t row) |
int |
double-click, or Enter/Space | - |
Expander |
on_toggle |
void(bool open) |
bool |
header clicked, or Space/Enter | set_open |
Splitter |
on_change |
void(float fraction) |
float |
divider dragged, or keys | set_fraction |
Menu |
on_open / on_close |
void() |
nothing | about to open / after it closed (any reason) | - |
Dialog (and MessageBox, FileBrowser) |
on_close |
void() |
nothing | closed by any means, once per close | - |
FileBrowser |
on_pick |
void(std::string path) |
str |
a file or folder chosen | - |
Row indices for TreeView are positions in the list you passed to
set_rows, whether or not the row is currently visible.
Callbacks passed when adding items#
Some widgets take the callback together with the item it belongs to:
| API | Callback | Runs when |
|---|---|---|
Menu::add_item(label, fn, hint, enabled) |
void() |
the item is chosen (then the menus close) |
Menu::add_checkable(label, is_checked, toggle, ...) |
bool() and void() |
is_checked is asked at paint time; toggle runs when chosen |
Toolbar::add_button(icon, fn, tooltip) |
void() |
the button is clicked |
MessageBox::add_button(label, fn) |
void() |
the button is clicked (then the box closes) |
Context::add_shortcut(key, mods, fn) |
void() |
the key chord is pressed anywhere (a modifier is required) |
Hooks that customise rather than notify#
These are called by the widget or the Context when they need something from you, not in response to the user:
| API | Signature | Purpose |
|---|---|---|
DragValue::set_format(fn) |
std::string(float) |
format the shown value |
IconButton::set_icon_painter(fn) |
void(DrawList&, Rect, Color) |
draw a custom icon |
Context::set_clipboard_source / set_clipboard_sink |
std::string() / void(std::string) |
connect the system clipboard (the window backends do this for you) |
Context::set_cursor_host(fn) |
void(Cursor) |
change the mouse cursor shape (likewise) |
Captures and lifetime#
C++. A callback lives as long as its widget. Whatever its lambda captures must outlive the widget, or the callback will read freed memory.
- Capturing other widgets by reference (
[&count]) is safe while they stay in the tree. Widgets are owned by the tree, andadd<T>()returns a reference that stays valid until that widget is removed. - Capturing locals by reference (
[&clicks]) is only safe if the locals outlive the UI, for example locals ofmainthat also owns the event loop. Otherwise keep app state in an object that outlives the tree and capture a pointer or reference to it. - If a widget is removed, its callbacks go with it. Remove a widget before destroying what its callbacks capture.
Python. Closures keep what they reference alive, so the usual Python
rules apply. A callback that captures its own widget forms a reference
cycle through the C++ tree; App.close(), or leaving with slikui.App(...),
breaks those cycles.
Lower level: events#
Callbacks cover what the built-in widgets do. For a widget of your own, or
to watch raw input, override on_event and handle Click, KeyPress,
MouseMove and the other events directly. See
Input & events for the event vocabulary and routing, and
Custom widgets for writing a widget.