From a6f28482c108ae8dcfa7e05bb76eb58e63b427de Mon Sep 17 00:00:00 2001 From: Peder Bergan Date: Mon, 5 Oct 2026 19:48:29 +0200 Subject: [PATCH] Add `RichText::color_override` to read the explicit text color (#8564) Expose the optional color set by `RichText::color()` so callers can read it without keeping duplicate state. `color_override()` returns the explicit override; theme and widget color resolution remain unchanged. * Closes * [x] I have followed the instructions in the PR template --- crates/egui/src/widget_text.rs | 60 +++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/egui/src/widget_text.rs b/crates/egui/src/widget_text.rs index e879b9c6..5887cf41 100644 --- a/crates/egui/src/widget_text.rs +++ b/crates/egui/src/widget_text.rs @@ -322,6 +322,26 @@ impl RichText { self } + /// The explicit text color set by [`Self::color`], if any. + /// + /// This does not resolve colors from [`Self::strong`], [`Self::weak`], + /// the style, or the widget that paints the text. + /// + /// ``` + /// use egui::{Color32, RichText}; + /// + /// let text = RichText::new("Hello"); + /// assert_eq!(text.color_override(), None); + /// assert_eq!(text.color_override().unwrap_or(Color32::WHITE), Color32::WHITE); + /// + /// let text = text.color(Color32::RED); + /// assert_eq!(text.color_override(), Some(Color32::RED)); + /// ``` + #[inline] + pub fn color_override(&self) -> Option { + self.text_color + } + /// Read the font height of the selected text style. /// /// Returns a value rounded to [`emath::GUI_ROUNDING`]. @@ -930,7 +950,45 @@ impl From> for WidgetText { #[cfg(test)] mod tests { - use crate::WidgetText; + use crate::{Color32, RichText, Visuals, WidgetText}; + + #[test] + fn rich_text_color_override_is_explicit() { + let visuals = Visuals { + override_text_color: Some(Color32::GREEN), + ..Visuals::default() + }; + for (text, resolved_color) in [ + (RichText::new("plain"), visuals.override_text_color), + ( + RichText::new("strong").strong(), + Some(visuals.strong_text_color()), + ), + ( + RichText::new("weak").weak(), + Some(visuals.weak_text_color()), + ), + ] { + assert_eq!(text.color_override(), None); + assert_eq!(text.get_text_color(&visuals), resolved_color); + + for color in [Color32::RED, Color32::TRANSPARENT, Color32::PLACEHOLDER] { + let colored = text.clone().color(color).strong().weak(); + assert_eq!(colored.color_override(), Some(color)); + assert_eq!(colored.get_text_color(&visuals), Some(color)); + } + } + } + + #[test] + fn rich_text_color_override_tracks_latest_color() { + let text = RichText::new("Hello").color(Color32::RED); + assert_eq!(text.color_override(), Some(Color32::RED)); + + let text = text.color(Color32::BLUE); + assert_eq!(text.color_override(), Some(Color32::BLUE)); + assert_eq!(text.text(), "Hello"); + } #[test] fn ensure_small_widget_text() {