0

If I have a widget, say a checkbox, in a panel in an egui/frame application, and I want something in a different panel whose behaviour depends on the value of that checkbox, is there either a direct way of accessing this value from one widget to the other, or a recommended/documented pattern to do this?

At the moment I'm achieving what I want by having variables in the widget that needs to read the values, and pass those from the main app code. It works, but it seems convoluted and mostly boiler plate. Given there's context, memory, ui, ... and widgets get names, I'm hoping there's a way of sharing info across widgets via any of these, but can't quite figure out how.

palako
  • 3,342
  • 2
  • 23
  • 33
  • I do the same in my application is due to the fact that the lifetime of a component is the refresh time. – Grzesiek Nov 19 '22 at 09:58

1 Answers1

0

When using eframe, a common pattern is to put all of the program's state as fields on the struct implementing the eframe::App trait and writing functions containing GUI code as member functions of that struct. This is what the official eframe_template does.

For example:

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"

Result:

screenshot

Kiuhrly
  • 52
  • 6