How do I "handle" an event in a control? #1124
-
My scenario: I'm using a code editor to maintain some text, and want to execute a certain behavior when I perform a CTRL+Enter while the control has focus. I have something working, though it feels a bit sketchy: let mut editor_text = String::new();
let editor = ui.add(
egui::TextEdit::multiline(&mut editor_text)
.code_editor()
.desired_width(f32::INFINITY)
);
let events = &ui.input().events;
if editor.has_focus() && events.iter().any(|evt| match evt {
Event::Key { key, modifiers, pressed } => {
key == &Key::Enter && *pressed && modifiers.ctrl
},
_ => false
}) {
perform_behavior();
} My dilemma: I can successfully perform the behavior as intended, but the CTRL+Enter sequence also causes the text contents of the control to change. This isn't a big deal given my use-case, but it does help to pose a broader question of how to correctly handle and dequeue such events prior to a control processing them. Scanning through code and examples didn't turn anything up, though maybe I missed something? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I think you should fork egui and fix something here egui/egui/src/widgets/text_edit/builder.rs Line 727 in ad54187 |
Beta Was this translation helpful? Give feedback.
-
Good question! I haven't thought through this use case much yet. I think the only solution is to catch the events before running the let text_edit_id = Id::new("my_code_editor");
let editor_has_focus = ui.ctx().memory().has_focus(self.id);
if editor_has_focus && events.iter().any(|evt|
matches!(evt,
Event::Key { key, modifiers, pressed }
if key == &Key::Enter && *pressed && modifiers.ctrl
)) {
ui.ctx().memory().surrender_focus(self.id);
perform_behavior();
}
let editor = ui.add(
egui::TextEdit::multiline(&mut editor_text)
.id(text_edit_id)
.code_editor()
.desired_width(f32::INFINITY)
); |
Beta Was this translation helpful? Give feedback.
Good question! I haven't thought through this use case much yet. I think the only solution is to catch the events before running the
TextEdit
code. Perhaps something like this: