【问题标题】:How to access egui/eframe values from other widgets?如何从其他小部件访问 egui/eframe 值?
【发布时间】:2023-02-21 03:29:57
【问题描述】:

如果我在 egui/frame 应用程序的面板中有一个小部件,比如一个复选框,并且我想要另一个面板中的某些东西,其行为取决于该复选框的值,是否有直接的方法从一个访问此值小部件到另一个,或者推荐/记录的模式来做到这一点?

目前,我正在通过在需要读取值的小部件中使用变量并从主应用程序代码传递这些变量来实现我想要的。它有效,但它看起来很复杂,而且主要是样板。考虑到上下文、内存、用户界面...和小部件获取名称,我希望有一种方法可以通过其中任何一个在小部件之间共享信息,但不太清楚如何实现。

【问题讨论】:

  • 我在我的应用程序中做同样的事情是因为组件的生命周期是刷新时间。

标签: rust egui eframe


【解决方案1】:

使用 eframe 时,一个常见的模式是将所有程序的状态作为字段放在实现 eframe::App 特征的结构上,并将包含 GUI 代码的函数编写为该结构的成员函数。官方eframe_template就是这么干的。

例如:

src/main.rs

use eframe::egui;

#[derive(Default)]
struct MyEguiApp {
    checkbox_ticked: bool,
}

impl MyEguiApp {
    fn left_panel(&mut self, ctx: &egui::Context) {
        egui::SidePanel::new(egui::panel::Side::Left, "left_panel").show(ctx, |ui| {
            ui.checkbox(&mut self.checkbox_ticked, "Checkbox");
        });
    }

    fn central_panel(&self, ctx: &egui::Context) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.label(format!(
                "The checkbox is {}.",
                if self.checkbox_ticked {
                    "ticked"
                } else {
                    "unticked"
                }
            ));
        });
    }

    fn new(_cc: &eframe::CreationContext) -> Self {
        Self::default()
    }
}

impl eframe::App for MyEguiApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        self.left_panel(ctx);
        self.central_panel(ctx);
    }
}

fn main() {
    let native_options = eframe::NativeOptions::default();
    eframe::run_native(
        "My egui App",
        native_options,
        Box::new(|cc| Box::new(MyEguiApp::new(cc))),
    );
}

Cargo.toml

[package]
name = "eframetest"
version = "0.1.0"
edition = "2021"

[dependencies]
eframe = "0.21"

结果:

screenshot

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多