egui Dropdown Menus in Rust — ComboBox + FontId + RichText | Ep 13
Video: egui Dropdown Menus in Rust — ComboBox + FontId + RichText | Ep 13 by Taught by Celeste AI - AI Coding Coach
Watch full page →egui Dropdown Menus in Rust — ComboBox + FontId + RichText
This tutorial demonstrates how to build a font preview application in Rust using the egui library. You'll learn to create dropdown menus with ComboBox, customize font rendering using FontId and RichText, and manage UI state safely with enums.
Code
use egui::{ComboBox, FontId, RichText, Ui};
// Enum for font styles with helper methods
#[derive(PartialEq, Clone, Copy)]
enum FontStyle {
Monospace,
Proportional,
}
impl FontStyle {
fn label(&self) -> &'static str {
match self {
FontStyle::Monospace => "Monospace",
FontStyle::Proportional => "Proportional",
}
}
}
// Enum for font sizes with helper methods
#[derive(PartialEq, Clone, Copy)]
enum FontSize {
Small,
Medium,
Large,
}
impl FontSize {
fn size(&self) -> f32 {
match self {
FontSize::Small => 12.0,
FontSize::Medium => 18.0,
FontSize::Large => 24.0,
}
}
}
// Application state holding selected font style and size
struct MyApp {
font_style: FontStyle,
font_size: FontSize,
preview_text: String,
}
impl Default for MyApp {
fn default() -> Self {
Self {
font_style: FontStyle::Monospace,
font_size: FontSize::Medium,
preview_text: "The quick brown fox jumps over the lazy dog.".to_owned(),
}
}
}
impl MyApp {
fn ui(&mut self, ui: &mut Ui) {
// Font style dropdown menu
ComboBox::from_id_salt("font_style_combo", ui)
.selected_text(self.font_style.label())
.show_ui(ui, |ui| {
for &style in &[FontStyle::Monospace, FontStyle::Proportional] {
ui.selectable_value(&mut self.font_style, style, style.label());
}
});
// Font size dropdown menu
ComboBox::from_id_salt("font_size_combo", ui)
.selected_text(format!("{:.0} pt", self.font_size.size()))
.show_ui(ui, |ui| {
for &size in &[FontSize::Small, FontSize::Medium, FontSize::Large] {
ui.selectable_value(&mut self.font_size, size, format!("{:.0} pt", size.size()));
}
});
// Text input for preview
ui.text_edit_singleline(&mut self.preview_text);
// Render preview text with selected font and size
let font_id = FontId::new(self.font_size.size(), match self.font_style {
FontStyle::Monospace => egui::FontFamily::Monospace,
FontStyle::Proportional => egui::FontFamily::Proportional,
});
ui.label(RichText::new(&self.preview_text).font(font_id));
}
}
Key Points
- Use
ComboBox::from_id_saltto create uniquely identified dropdown menus in egui. selected_textshows the current selection, whileselectable_valuecreates selectable options.FontId::newcombines font size and family to customize text rendering.RichTextallows styling text with custom fonts inside the UI.- Enums with helper methods provide type-safe, readable state management for UI selections.