Back to Blog

Rust egui Grid Layout — Build an Aligned Contact Form (Ep 8)

Sandy LaneSandy Lane

Video: Rust egui Grid Layout — Build an Aligned Contact Form (Ep 8) by Taught by Celeste AI - AI Coding Coach

Watch full page →

Rust egui Grid Layout — Build an Aligned Contact Form

In this tutorial, you'll learn how to create a clean, aligned contact form using egui's Grid layout in Rust. By leveraging egui::Grid, you can neatly arrange labeled input fields like Name, Email, Phone, and Subject in rows and columns with consistent spacing and alignment.

Code

use eframe::egui::{self, Grid, TextEdit};

fn contact_form_ui(ui: &mut egui::Ui, name: &mut String, email: &mut String, phone: &mut String, subject: &mut String) {
  // Create a new grid with a unique ID and 2 columns (label + input)
  Grid::new("contact_form_grid")
    .num_columns(2)
    .spacing([10.0, 8.0]) // horizontal and vertical spacing between cells
    .show(ui, |ui| {
      ui.label("Name:");       // Label cell
      ui.add(TextEdit::singleline(name)); // Input cell
      ui.end_row();            // End first row

      ui.label("Email:");
      ui.add(TextEdit::singleline(email));
      ui.end_row();

      ui.label("Phone:");
      ui.add(TextEdit::singleline(phone));
      ui.end_row();

      ui.label("Subject:");
      ui.add(TextEdit::singleline(subject));
      ui.end_row();
    });

  // Optionally, display a summary or submit button below the grid
  ui.separator();
  ui.label(format!("Submitting: {}, {}, {}, {}", name, email, phone, subject));
}

Key Points

  • Use egui::Grid::new() with a unique ID to create aligned rows and columns.
  • Call ui.end_row() after each row to properly separate grid rows.
  • Configure the number of columns with .num_columns() to control layout structure.
  • Adjust spacing between grid cells using .spacing([horizontal, vertical]) for cleaner appearance.
  • Multiple grids can coexist by assigning different IDs to each grid instance.