From 0fb7875251e25254a058aa0ca600079143233daa Mon Sep 17 00:00:00 2001 From: Lucas Meurer Date: Mon, 24 Aug 2026 15:27:29 +0200 Subject: [PATCH] Add some more helpers --- crates/egui/src/ui_stack.rs | 9 +++++++++ crates/egui/src/widget_style/classes.rs | 11 +++++++++++ crates/egui/src/widget_style/mod.rs | 7 +++++++ 3 files changed, 27 insertions(+) diff --git a/crates/egui/src/ui_stack.rs b/crates/egui/src/ui_stack.rs index 59b02db90..d9d09f9d5 100644 --- a/crates/egui/src/ui_stack.rs +++ b/crates/egui/src/ui_stack.rs @@ -297,6 +297,15 @@ impl UiStack { self.iter() .any(|node| node.classes.has_class(class.clone())) } + + /// Read a value from the classes up the stack, nearest node first. + /// + /// This is how an inherited property works in a stylesheet: a container states it once, and + /// everything inside picks it up. The nearest [`crate::Ui`] wins, so an inner container can + /// override an outer one. + pub fn inherited(&self, from_classes: impl Fn(&Classes) -> Option) -> Option { + self.iter().find_map(|node| from_classes(&node.classes)) + } } // ---------------------------------------------------------------------------- diff --git a/crates/egui/src/widget_style/classes.rs b/crates/egui/src/widget_style/classes.rs index 41aabf3f4..5e91d16d6 100644 --- a/crates/egui/src/widget_style/classes.rs +++ b/crates/egui/src/widget_style/classes.rs @@ -158,6 +158,17 @@ pub trait HasClasses { fn as_slice(&self) -> &[ClassName] { &self.classes().classes } + + /// The last class that names a `T`, if any. + /// + /// Scanning backwards is what makes the last class win, so a widget given two classes of the + /// same kind takes the one set last — the way a later stylesheet rule overrides an earlier one. + fn last_class(&self, from_class_name: impl Fn(&str) -> Option) -> Option { + self.as_slice() + .iter() + .rev() + .find_map(|class| from_class_name(class)) + } } #[cfg(test)] diff --git a/crates/egui/src/widget_style/mod.rs b/crates/egui/src/widget_style/mod.rs index b2ab8430b..e365e709f 100644 --- a/crates/egui/src/widget_style/mod.rs +++ b/crates/egui/src/widget_style/mod.rs @@ -238,4 +238,11 @@ impl StyleArgs<'_> { let class = class.into(); self.classes.has_class(class.clone()) || self.stack.has_class(class) } + + /// Read a value from the widget's own classes, falling back to the [`crate::Ui`]s it sits in. + /// + /// See [`UiStack::inherited`] for how the fallback resolves. + pub fn inherited(&self, from_classes: impl Fn(&Classes) -> Option) -> Option { + from_classes(self.classes).or_else(|| self.stack.inherited(from_classes)) + } }