Your first application
Build a counter step by step — the component, the signal, the view, the style sheet, and the entry point.
In this tutorial you build a small counter with two buttons, then walk through it piece by piece. Along the way you meet the ideas the rest of the guide builds on: components, signals, views, and reactive holes.
The complete program
Replace src/main.rs in the project from Installation with
this:
use zgui::prelude::*;
#[component]
fn Counter() -> impl IntoView {
let (count, set_count) = signal(0);
view! {
column(class = "counter") {
label(class = "counter__caption") {"Count"}
text(class = "counter__value") {{move || count.get().to_string()}}
row(class = "counter__buttons") {
control(
class = "button",
on:click = move |_| set_count.update(|n| *n -= 1)
) {
"-"
}
control(
class = "button button--primary",
on:click = move |_| set_count.update(|n| *n += 1)
) {
"+"
}
}
}
}
}
const SHEET: &str = css!(
":root {
background-color: #12141a;
color: #e8ecf4;
font-family: sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.counter {
align-items: center;
gap: 12px;
padding: 32px 48px;
border-radius: 16px;
border: 1px solid #262b36;
background-color: #191d26;
}
.counter__caption {
font-size: 13px;
letter-spacing: 2px;
color: #7d879b;
}
.counter__value {
font-size: 64px;
font-weight: 700;
line-height: 1.1;
}
.counter__buttons { gap: 12px; }
.button {
padding: 10px 22px;
border-radius: 10px;
border: 1px solid #2f3646;
background-color: #232936;
color: #e8ecf4;
font-size: 20px;
line-height: 1;
text-align: center;
}
.button:hover { background-color: #2b3243; }
.button--primary {
background-color: #3b6cf6;
border-color: #3b6cf6;
}"
);
fn main() -> Result<(), zgui::Error> {
app()
.with_title("Counter")
.with_size(360.0, 300.0)
.with_stylesheet(SHEET)
.run(|| view! { Counter() })
}Run it with cargo run. A window opens with a number and two buttons that change it. The sections
below explain the program from top to bottom.
Import the prelude
use zgui::prelude::*;The prelude brings in everything you need to write an interface: reactive primitives, the
view!, component, and css! macros, attribute and event types, control flow, and the app()
entry point.
Reading and writing a signal are trait methods, so those traits must be in scope. That is the main reason to import the prelude. Every name in it is also available at its own path.
Define a component
#[component]
fn Counter() -> impl IntoView {#[component] turns a function into a component: a plain function that builds part of the
interface and returns it. Component names start with a capital letter.
impl IntoView covers anything that can be shown: a string, a number, a tuple, an Option, a
closure, an element, or a view! block.
A component runs once. Counter() is called when the interface is built and never again,
however often the count changes. Anything that changes later changes through a signal.
Create state with a signal
let (count, set_count) = signal(0);signal(0) creates state and returns two handles: a reader and a writer.
When a closure that zgui is tracking reads count, zgui records the dependency. When you write
through set_count, every closure that read count runs again. Nothing else in the window is
touched.
RwSignal::new(0) is the same signal with both halves in one handle. A split pair is useful when
you pass the writer and the reader to different places.
Describe the interface
view! {
column(class = "counter") {
label(class = "counter__caption") {"Count"}
...
}
}view! describes part of the document. Each node is a call with a block:
- a name, such as
columnorcontrol, which is an element or a component; - attributes in parentheses, comma-separated, written
name = value; - children in braces.
You can leave out the parentheses or the block, but not both. Children follow each other with no separator. A child is a string literal, a braced expression, or another call.
column(class = "a") { // attributes and children
text {"hello"} // children only
spacer() // attributes only (here, none)
}Built-in elements
zgui has sixteen built-in elements. This program uses five, and each has a default layout:
| Name | What it is | Default layout |
|---|---|---|
column | children stacked top to bottom | vertical flex container |
row | children in a line | horizontal flex container |
text | a run of text | inline |
label | text that names something else | inline |
control | something the user operates; focusable | block |
There is no div. A generic container is box. The full list is in
Elements.
Show a changing value
text(class = "counter__value") {{move || count.get().to_string()}}The double braces are intentional. The outer pair is the children block. The inner pair is an expression child, and the expression is a closure.
A closure child is a reactive hole. zgui runs it once for the initial text, and again whenever something it read changes. Only the text node is updated, not the element or its siblings.
text {{move || count.get().to_string()}} // updates whenever count changes
text {{count.get().to_string()}} // written once, never updatedBoth compile. A closure is reactive; a plain String is not.
Forgetting move || is the most common mistake. The interface renders correctly once and then
never changes.
Handle a click
control(on:click = move |_| set_count.update(|n| *n += 1)) { "+" }on:click attaches a listener. The text after on: is the event name, and the closure's argument
type is inferred from it.
set_count.update(|n| *n += 1) changes the value in place. set_count.set(5) replaces it.
A write does not run dependent closures immediately. It marks them, and zgui runs each one once later in the same frame. A listener that writes five signals still causes one update pass.
Style it with CSS
const SHEET: &str = css!(":root { ... } .counter { ... }");css! checks the sheet's structure at compile time and reports errors at the line and column
inside the sheet. It does not check property names. It returns a &'static str, so it works in a
const.
The CSS is ordinary CSS. Three points matter now:
:rootis the document root. Put the window background, base text colour, and font family there; they inherit.- Element names are selectors.
control { ... }styles everycontrol. Your rules override zgui's default sheet, socolumn { flex-direction: row }works. :hover,:focus, and other states work because zgui tracks the pointer and focus itself.
Styling covers the full model.
Open the window
fn main() -> Result<(), zgui::Error> {
app()
.with_title("Counter")
.with_size(360.0, 300.0)
.with_stylesheet(SHEET)
.run(|| view! { Counter() })
}app() starts a builder. run opens the primary window, runs the event loop, and returns when the
application exits. The closure builds the window's root view.
The builder has methods for the window's size limits, position, frame, icon, and theme, and for application-wide settings such as fonts and shared state. They are listed in Application builder methods below.
What happens when you click
Between your click and the new number on screen, zgui does the following:
The platform reports a pointer event at a pixel position.
zgui finds the element under it using the geometry from the last frame, and dispatches the event along the path from the root to that element.
Your listener runs. set_count.update(...) writes the signal and marks the closures that read
count.
The marked closure runs once and writes the new string into the text node.
Only affected work is redone. The changed paragraph is reshaped and its box re-measured. Nothing else in the document needs work.
The renderer redraws the damaged area, the rectangle around the number. Every other pixel is kept from the previous frame.
Application builder methods
| Method | Sets |
|---|---|
with_title | the window title |
with_size | the starting size, in CSS pixels |
with_min_size, with_max_size, with_resizable | size constraints |
with_position, with_maximized, with_fullscreen | the starting window state |
with_decorations, with_transparent, with_title_buttons | the window frame, transparency, and macOS title-bar button placement |
with_level, with_icon, with_theme | stacking level, window icon, light or dark preference |
with_stylesheet | the application's style sheet |
with_application_id | the identifier the desktop uses for icons and window rules |
with_context | state shared by every window |
with_menu | the application menu (macOS) |
with_exit_policy | when a multi-window application exits |
with_fonts | the fonts to use instead of the system's |
with_style_threads, with_layout_threads | worker counts for styling and layout |
To open more windows, use use_windows(). See Windows.
Shipping covers the application identifier and the menu.