eguiのウィジェット配置はupdate関数内で完結するため、icedとは異なる設計思想を持つ。以下では最小構成でボタンとラベルを表示し、クリックイベントを拾う手順を示す。
基本構成
use eframe::egui;
struct MyApp {
counter: u32,
message: String,
}
impl Default for MyApp {
fn default() -> Self {
Self {
counter: 0,
message: "初期メッセージ".to_string(),
}
}
}
impl eframe::App for MyApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("egui ウィジェットサンプル");
// ラベル表示
ui.label(&format!("カウント: {}", self.counter));
// 水平レイアウトでボタンを並列配置
ui.horizontal(|ui| {
if ui.button("増加").clicked() {
self.counter += 1;
self.message = format!("{}回クリックされました", self.counter);
}
if ui.button("リセット").clicked() {
self.counter = 0;
self.message = "リセットされました".to_string();
}
});
// 動的メッセージラベル
ui.label(&self.message);
});
}
}
fn main() {
let options = eframe::NativeOptions::default();
eframe::run_native(
"eguiウィジェットデモ",
options,
Box::new(|_cc| Ok(Box::new(MyApp::default()))),
)
.unwrap();
}
レイアウトの工夫
ボタンを縦に並べる場合はui.verticalを使用する。
ui.vertical(|ui| {
ui.add_space(10.0);
if ui.add(egui::Button::new("縦配置ボタン")).clicked() {
println!("縦ボタンが押されました");
}
ui.add_space(5.0);
ui.small("小さなラベル");
});
スタイルのカスタマイズ
ボタンに色やサイズを指定する例。
let custom_btn = egui::Button::new("カスタムボタン")
.fill(egui::Color32::from_rgb(100, 200, 150))
.min_size(egui::Vec2::new(120.0, 40.0));
if ui.add(custom_btn).clicked() {
// 処理
}
日本語フォント設定
別モジュールに切り出したfont_loader.rsを利用して日本語を表示する例。
mod font_loader;
impl MyApp {
fn new(cc: &eframe::CreationContext<'_>) -> Self {
font_loader::setup_custom_fonts(
&cc.egui_ctx,
include_bytes!("../assets/NotoSansJP-Regular.otf"),
);
Self::default()
}
}
これにより、ボタンやラベルに日本語を含めることができる。