跳转至

第十三章 实战技巧与常见问题

本章是一些从源码和 FAQ 里整理出来的实战经验。代码片段都对照 egui-0.37.0 / eframe-0.37.0 编译检查过(涉及 glow、persistence 的另有说明)。

13.1 输入读取

// 键盘
ctx.input(|i| i.key_down(egui::Key::A));
ctx.input(|i| i.key_pressed(egui::Key::Enter));

// 鼠标
ctx.input(|i| i.pointer.primary_clicked());   // 这一帧点了左键
ctx.input(|i| i.pointer.is_decidedly_dragging()); // 正在拖
let pos: Option<egui::Pos2> = ctx.input(|i| i.pointer.hover_pos());

// 滚轮
let scroll = ctx.input(|i| i.smooth_scroll_delta);

// 修饰键
let ctrl  = ctx.input(|i| i.modifiers.ctrl);
let shift = ctx.input(|i| i.modifiers.shift);
let alt   = ctx.input(|i| i.modifiers.alt);
let cmd   = ctx.input(|i| i.modifiers.command); // Windows/Linux 是 Ctrl,macOS 是 Cmd

// 剪贴板
let s: Option<String> = ctx.input(|i| i.raw.events.iter().find_map(|e| {
    if let egui::Event::Paste(s) = e { Some(s.clone()) } else { None }
}));

都用 ctx.input(|i| ...) 闭包形式,别手动拿锁。Ui 可以直接当 Context 用,所以在 ui 里写 ui.input(|i| ...) 也行。

13.2 自定义快捷键

在 App::raw_input_hook 里拦截/注入事件:

fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
    // 例如:吞掉某些按键
    raw.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::F1, .. }));
}

或在 logic 里检测:

fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
    if ctx.input(|i| i.key_pressed(egui::Key::S) && i.modifiers.ctrl) {
        self.save();
    }
}

想跨平台(macOS 用 Cmd+S)并且“吃掉”这个按键,让别的控件不再收到它,用 consume_shortcut:

let save = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::S);
if ctx.input_mut(|i| i.consume_shortcut(&save)) {
    self.save();
}

13.3 异步任务

GUI 线程绝不能阻塞——一 .await 整个 UI 就卡住。常见做法:

  • 通道(std::sync::mpsc):后台线程发,GUI 线程 try_recv。
  • Arc<Mutex<T>>:后台线程写,GUI 线程读。
  • poll_promise::Promise / eventuals::Eventual / tokio::sync::watch。

例子:用 mpsc 在后台跑任务,每发一条消息就叫醒 UI:

use std::sync::mpsc;

struct MyApp {
    rx: mpsc::Receiver<String>,
    logs: Vec<String>,
}

impl MyApp {
    fn new(cc: &eframe::CreationContext<'_>) -> Self {
        let (tx, rx) = mpsc::channel();
        let ctx = cc.egui_ctx.clone(); // Context 可以 clone 后送到别的线程
        std::thread::spawn(move || {
            for i in 0u32.. {
                std::thread::sleep(std::time::Duration::from_secs(1));
                if tx.send(format!("tick {i}")).is_err() {
                    break; // 接收端没了,说明程序在退出
                }
                ctx.request_repaint(); // 空闲时 egui 不会自己重绘,发完消息要主动叫醒
            }
        });
        Self { rx, logs: Vec::new() }
    }
}

impl eframe::App for MyApp {
    fn logic(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) {
        // 非阻塞地取消息
        while let Ok(msg) = self.rx.try_recv() {
            self.logs.push(msg);
        }
    }

    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ui, |ui| {
            for log in &self.logs {
                ui.label(log);
            }
        });
    }
}

不要在 logic 里无条件 request_repaint():那会让程序永远满帧重绘、占满 CPU(见 13.12)。让产生数据的一方在数据到达时再请求重绘。

13.4 文件对话框

用 rfd(同时支持桌面和网页):

// 在 async 块/任务里调用,返回 Option<rfd::FileHandle>
let file = rfd::AsyncFileDialog::new()
    .add_filter("图片", &["png", "jpg"])
    .pick_file()
    .await;

记得用 async 版本,并把它放到后台线程或异步运行时里跑(结果用 13.3 的通道送回 App),别阻塞 GUI。

13.5 持久化窗口大小/位置

开 persistence feature,eframe 会自动存窗口位置/大小和 egui::Memory。ViewportBuilder::with_app_id(...) 决定存到哪个目录(没设就用 run_native 的第一个参数)。你自己的数据不会自动存,要在 App::save 里写,详见 12.8。

13.6 接收拖入的文件

egui 本身不接触操作系统,拖文件进窗口靠集成:

  • 桌面:egui-winit 把 winit 的 DroppedFile 事件转成 egui::RawInput::dropped_files。
  • 读取:
ctx.input(|i| {
    for file in &i.raw.dropped_files {
        println!("{:?}", file.path()); // 注意是方法,返回 &Path
        // 桌面上读内容:file.bytes() -> Result<Vec<u8>, String>
    }
});

dropped_files 的元素是 Arc<dyn DroppedFile + Send + Sync>(egui::DroppedFileHandle)。几点注意:

平台/情况 行为
桌面 path() 是绝对路径,bytes() 同步读文件。
网页 path() 只有文件名;读内容要用异步的 bytes_async()。
Windows 上 ViewportBuilder::with_drag_and_drop(false) dropped_files 恒为空。

拖到一半(还没松手)的文件在 i.raw.hovered_files,可以用来画“松手即上传”的提示。

13.7 自动重绘与节能

egui 默认只在有交互或动画时重绘。空闲时不占 CPU。

如果你想定时刷新(比如显示时间),请求“一段时间后再画一帧”:

ctx.request_repaint_after(std::time::Duration::from_secs(1));

它只保证到点会重绘,不会让程序一直满帧跑。或从其它线程触发:

let ctx2 = ctx.clone();
std::thread::spawn(move || {
    std::thread::sleep(std::time::Duration::from_millis(500));
    ctx2.request_repaint();
});

Context 可以被 clone 然后传到任何线程。

13.8 长列表虚拟化

ScrollArea 只负责裁剪显示,不会替你跳过闭包里的 ui.add:10000 个控件每帧都要布局一遍,照样慢(egui README 也把“很长的滚动区域”列为 immediate mode 的 CPU 开销来源)。

行高固定时,直接用 ScrollArea::show_rows,它只会把可见的行号区间交给你:

egui::ScrollArea::vertical().show_rows(ui, row_height, data.len(), |ui, row_range| {
    for i in row_range {
        ui.label(format!("item {}", data[i]));
    }
});

row_height 是不含间距的行高,常用 ui.text_style_height(&egui::TextStyle::Body) 取。

方法 适用 给你什么
ScrollArea::show_rows 每行等高 可见的行号区间 Range<usize>。
ScrollArea::show_viewport 行高不固定,自己算 可见区域 Rect(相对内容左上角)。

13.9 调试

悬停看调用栈

ctx.set_debug_on_hover(true);  // 悬停时显示创建这个控件的代码调用栈

这个选项只在 debug 构建 + 原生 下有效,并且要求 egui 开了 callstack feature(在你自己的 Cargo.toml 里加 egui = { version = "0.37", features = ["callstack"] })。开了 callstack 之后,debug 构建里同时按住所有修饰键(Ctrl+Shift+Alt+Cmd)再悬停控件,不用调 set_debug_on_hover 也能看到。

调试绘制开关

控件边界、ID 冲突、布局撑宽等调试信息,由 Style::debug(DebugOptions)里的开关控制:

ctx.global_style_mut(|style| {
    style.debug.show_interactive_widgets = true; // 给所有可交互控件画框
    style.debug.show_widget_hits = true;         // 显示鼠标下命中了哪些控件
    style.debug.show_unaligned = true;           // 高亮没对齐像素网格的控件
    style.debug.show_expand_width = true;        // 谁把父容器撑宽了
    style.debug.show_expand_height = true;       // 谁把父容器撑高了
    style.debug.show_focused_widget = true;      // 高亮当前焦点控件
});

内置检查面板

Context 上有几个现成的“检查器”UI,传一个 &mut Ui 就能显示:

let ctx = ui.ctx().clone();
egui::CollapsingHeader::new("Inspection").show(ui, |ui| ctx.inspection_ui(ui)); // 运行状态:帧数、指针/键盘占用、焦点控件、输入输出
egui::CollapsingHeader::new("Settings").show(ui, |ui| ctx.settings_ui(ui));     // 样式、tessellation 选项、字体微调
egui::CollapsingHeader::new("Memory").show(ui, |ui| ctx.memory_ui(ui));         // Memory 里存的状态(窗口位置、折叠状态等)

eframe 没有自带“按某个组合键弹出检查窗口”的功能,需要自己放一个按钮或快捷键去显示上面这些面板。

屏幕上打印变量

ctx.debug_text(format!("frame: {}", ctx.cumulative_frame_nr()));

文字会显示在光标旁边,只在 debug 构建里生效。

外部检查(eframe 的 inspection feature)

eframe 开了 inspection feature 后,用环境变量 EGUI_INSPECTION=1 启动程序,外部工具(如 egui_mcp)可以读取界面的无障碍树并发送事件。没开 feature 却设了环境变量,只会打印一条警告。

13.10 在 egui 里画 3D

两种方式:

PaintCallback(Shape::Callback)

egui 在绘制阶段调你的代码,用当时的渲染上下文画任意 3D。回调的具体类型取决于后端:

后端 回调类型 拿到什么
glow(需 glow feature,Renderer::Glow) egui_glow::CallbackFn &egui_glow::Painter,用 painter.gl() 取 glow::Context。
wgpu(eframe 默认) egui_wgpu::Callback::new_paint_callback(rect, impl CallbackTrait) CallbackTrait 的 prepare / finish_prepare / paint,能拿到 RenderPass 和 CallbackResources。

类型对不上的回调不会被画出来。glow 的写法(eframe 已重新导出 eframe::egui_glow 和 eframe::glow):

let callback = egui::PaintCallback {
    rect,
    callback: std::sync::Arc::new(eframe::egui_glow::CallbackFn::new(move |info, painter| {
        let gl = painter.gl();
        // 在这里用 gl 画 3D
    })),
};
ui.painter().add(callback);

参考示例:examples/custom_3d_glow/(glow),crates/egui_demo_app/src/apps/custom3d_wgpu.rs(wgpu)。

上面 glow 写法在开了 glow feature 的临时工程里 cargo check 通过;wgpu 的 CallbackTrait 实现也核对过签名。

渲染到纹理

把 3D 场景渲到纹理,转成 egui::TextureId,用 ui.image(...) 显示。具体怎么转看后端:

  • eframe + glow:frame.register_native_glow_texture(tex)(底层是 egui_glow::Painter::register_native_texture)。
  • egui-wgpu:用 Renderer::register_native_texture 等接口,或把资源放进 CallbackResources。

13.11 中文字体推荐

免费可商用中文字体:

  • 思源黑体(Source Han Sans):SourceHanSansCN-Regular.otf,最常用。
  • 思源宋体(Source Han Serif)。
  • 更纱黑体(Sarasa Gothic):等宽中文,适合代码编辑器。
  • Noto Sans CJK:Google 版的思源。

加载方法见 第十章。

不想往程序里打包几十 MB 字体文件的话,0.37 起可以用系统字体兜底:用 eframe 的桌面端什么都不用写——默认 feature system_fonts 会自动装上 egui_system_font_provider::SystemFontProvider,由 NativeOptions::system_font_fallback(默认 true)控制。只有不用 eframe(或 web)时才需要自己 ctx.add_font_provider(std::sync::Arc::new(egui_system_font_provider::SystemFontProvider::new())),见同一节的“更省事的办法”。

13.12 常见错误

“egui::Context was locked” / 死锁

你手动拿了 Context 的锁后又在闭包里调 egui API。改成 ctx.input(|i| ...) 这种闭包形式。

控件 ID 冲突

debug 构建下 egui 会在界面上直接画出警告(并标出冲突的控件),不会 panic;release 构建默认不检查。开关是 Options::warn_on_id_clash,默认值等于 cfg!(debug_assertions)。解决办法:用 ui.push_id("...", |ui| ...) 给重复结构加唯一前缀,或给 Window、ScrollArea 等换不同的 id。

CPU 一直占满 / 一直在重绘

可能是 request_repaint 被每帧调用,导致永远在重绘。检查 logic 和 ui 里有没有无条件 request_repaint;要定时刷新请用 request_repaint_after。

滑块/数值显示一闪一闪

常见原因是数值位数变化让文字宽度跟着变,布局就会抖。给 Slider / DragValue 固定小数位(.fixed_decimals(2))或给控件固定宽度。

重新设置字体不生效

ctx.set_fonts 覆盖整套已有字体(包括默认字体),而且要到下一个 pass 才生效(如果这一帧还没排过版则立刻生效)。如果你只是想加字体,用 ctx.add_font(FontInsert::new(...)),它按名字判重、保留已有字体。

Button 没反应

可能你套了 ui.disable()、ui.add_enabled_ui(false, ...) 或 ui.add_enabled(false, ...)。检查调用栈上有没有禁用。(旧的 ui.set_enabled(false) 在 0.37 里已经不存在了。)

升级到 0.37 后一堆编译错误

下面这些写法在 0.37 里要么已被删除(报“找不到”,不是警告),要么刚被弃用(还能编译,有警告)。“已删除”的那些在 egui-0.34.3 / eframe-0.34.3 里都还是 #[deprecated],在 0.35 被统一清理(见 CHANGELOG.md 里的 “Remove everything that was marked #[deprecated]”):

旧写法 新写法 0.37 里的状态
eframe::App::update(&mut self, ctx, frame) ui(&mut self, ui, frame) + 可选的 logic(&mut self, ctx, frame) 已删除
ctx.run(input, callback)(callback 收 &Context) ctx.run_ui(input, callback)(callback 收 &mut Ui) 已删除
SidePanel::left("id") / TopBottomPanel::top("id") Panel::left("id") / Panel::top("id") 已删除
CentralPanel::default().show(ctx, ..) CentralPanel::default().show(ui, ..) show 现在只收 &mut Ui;show_inside 是弃用别名
egui::menu::bar(ui, ..) egui::MenuBar::new().ui(ui, ..) 已删除
ctx.style() / style_mut / set_style ctx.global_style() / global_style_mut / set_global_style 已删除(ui.style() 不受影响)
Rounding::same(4.0) CornerRadius::same(4)(参数是 u8,不再是 f32) 已删除
visuals.widgets.noninteractive.rounding visuals.widgets.noninteractive.corner_radius 字段已改名
Frame::none() Frame::NONE(常量) 已删除
ui.set_enabled(false) ui.disable() / ui.add_enabled_ui(false, ..) / ui.add_enabled(false, ..) 已删除
Id::new("x") Id::unique("x")(全局唯一)或 IdSalt::new("x")(局部盐) 0.37 弃用
ui.id() ui.scope_id() 0.37 弃用
WidgetType::Checkbox Role::CheckBox WidgetType 本身是弃用别名,但有变体改名:Checkbox→CheckBox、TextEdit→TextInput、DragValue→SpinButton 等(完整对照见 egui-0.37.0/src/lib.rs)
WidgetInfo::labeled(WidgetType::Button, enabled, "文字") WidgetInfo::labeled(Role::Button, enabled, "文字") 参数类型换成 Role
egui = "0.36"(默认带内嵌字体) egui = { version = "0.37", features = ["default_fonts"] } default_fonts 不再是 egui 的默认 feature;eframe 默认仍开着它

最低支持的 Rust 版本(MSRV)从 0.36 起是 1.95,0.37 沿用。egui 各 crate 自己用 edition 2024;你的项目用哪个 edition 不受限制,本教程的示例工程用 edition = "2024"。

13.13 性能清单

  • 大列表用 ScrollArea::show_rows(只布局可见的行),见 13.8。
  • 别在 ui 闭包里做重计算(解析、IO),提前算好放 App 字段。
  • 复杂图片用 TextureHandle 缓存,别每帧重新上传。
  • 用 ui.is_rect_visible(rect) 跳过不可见绘制。
  • cargo run --release 测真实性能,debug 构建慢得多。

13.14 哪里继续学

  • 官方文档:https://docs.rs/egui
  • 在线 demo:https://www.egui.rs/#demo
  • 源码示例:examples/ 目录每个都值得跑一遍。
  • demo lib 源码:crates/egui_demo_lib/src/demo/ 是个“怎么用 egui 写各种控件”的活教材。
  • 更新日志:仓库根目录的 CHANGELOG.md,升级前先看“Breaking changes”。
  • GitHub Discussions:https://github.com/emilk/egui/discussions,问问题去这。
  • Discord:egui 官方 Discord 服务器。

13.15 写在最后

egui 的设计哲学是“简单直接”。如果你写代码时觉得“这也太绕了”,大概率是你想多了——回到“每帧画一遍、状态自己存”这两个原则,问题就清楚了。

祝玩得开心。