From e13cc69d76227434aa46682999e338497c2740fe Mon Sep 17 00:00:00 2001 From: jayzhudev <79593171+jayzhudev@users.noreply.github.com> Date: Sat, 6 Jan 2024 14:35:54 -0700 Subject: [PATCH] Add a public API for overriding plot legend traces' visibilities (#3534) Added a public API in `egui_plot -> legend` to allow `hidden_items` to be overridden in the plot legend widget. This allows convenient control of traces' visibilities the selection of traces from the application code. ### Example ```rust let legend_config = if plot_selection_changed { let hidden_items = match plot_selection { PlotSelection::SelectAll => Vec::new(), PlotSelection::DeselectAll => all_trace_names, }; Legend::default() .position(Corner::RightTop) .hidden_items(hidden_items) // Overrides `hidden_items` } else { Legend::default().position(Corner::RightTop) }; Plot::new(id) .legend(legend_config) .show(ui, draw_plot); ``` Closes . --------- Co-authored-by: Emil Ernerfeldt --- crates/egui_plot/src/legend.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/egui_plot/src/legend.rs b/crates/egui_plot/src/legend.rs index 0a0f459f2f8..2dd69c984ce 100644 --- a/crates/egui_plot/src/legend.rs +++ b/crates/egui_plot/src/legend.rs @@ -32,6 +32,9 @@ pub struct Legend { pub text_style: TextStyle, pub background_alpha: f32, pub position: Corner, + + /// Used for overriding the `hidden_items` set in [`LegendWidget`]. + hidden_items: Option>, } impl Default for Legend { @@ -40,6 +43,8 @@ impl Default for Legend { text_style: TextStyle::Body, background_alpha: 0.75, position: Corner::RightTop, + + hidden_items: None, } } } @@ -65,6 +70,17 @@ impl Legend { self.position = corner; self } + + /// Specifies hidden items in the legend configuration to override the existing ones. This + /// allows the legend traces' visibility to be controlled from the application code. + #[inline] + pub fn hidden_items(mut self, hidden_items: I) -> Self + where + I: IntoIterator, + { + self.hidden_items = Some(hidden_items.into_iter().collect()); + self + } } #[derive(Clone)] @@ -167,8 +183,11 @@ impl LegendWidget { rect: Rect, config: Legend, items: &[Box], - hidden_items: &ahash::HashSet, + hidden_items: &ahash::HashSet, // Existing hiddent items in the plot memory. ) -> Option { + // If `config.hidden_items` is not `None`, it is used. + let hidden_items = config.hidden_items.as_ref().unwrap_or(hidden_items); + // Collect the legend entries. If multiple items have the same name, they share a // checkbox. If their colors don't match, we pick a neutral color for the checkbox. let mut entries: BTreeMap = BTreeMap::new();