Rust egui Horizontal Layout — Build an Action Toolbar (Ep 6)
Video: Rust egui Horizontal Layout — Build an Action Toolbar (Ep 6) by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust egui Horizontal Layout — Build an Action Toolbar
In this tutorial, you'll learn how to arrange widgets side by side using egui's ui.horizontal() method to build a functional action toolbar. We'll create a row of buttons for Add, Remove, and Reset actions, along with live status and count displays, demonstrating how to group and organize GUI elements horizontally.
Code
fn ui_example(ui: &mut egui::Ui, count: &mut i32, status: &mut String) {
ui.horizontal(|ui| {
// Add button increases the count
if ui.button("Add").clicked() {
*count += 1;
*status = "Added".to_owned();
}
// Remove button decreases the count if possible
if ui.button("Remove").clicked() {
if *count > 0 {
*count -= 1;
*status = "Removed".to_owned();
}
}
// Reset button sets count to zero
if ui.button("Reset").clicked() {
*count = 0;
*status = "Reset".to_owned();
}
// Separator to visually divide buttons and status
ui.separator();
// Display current count and status side by side
ui.horizontal(|ui| {
ui.label("Count:");
ui.label(count.to_string());
});
ui.horizontal(|ui| {
ui.label("Status:");
ui.label(status);
});
});
}
Key Points
- Use
ui.horizontal(|ui| { ... })to arrange widgets side by side in a row. - Group related widgets inside closures to keep code organized and layout consistent.
- Mix buttons and labels freely within a horizontal layout to build interactive toolbars.
- Use
ui.separator()to visually separate sections within the same horizontal layout. - Multiple nested
ui.horizontal()calls can create label-value pairs aligned neatly.