From ccbddcfe951e01c55efd0ed19f2f2ab5edfad5d9 Mon Sep 17 00:00:00 2001 From: Emil Ernerfeldt Date: Sun, 20 Mar 2022 23:08:19 +0100 Subject: [PATCH] Add example of how to move text cursor in a TextEdit --- egui/src/lib.rs | 5 +++-- egui_demo_lib/src/apps/demo/text_edit.rs | 25 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/egui/src/lib.rs b/egui/src/lib.rs index e3a604150d4..c6ab4b0eafc 100644 --- a/egui/src/lib.rs +++ b/egui/src/lib.rs @@ -391,9 +391,10 @@ pub use epaint::{ }; pub mod text { + pub use crate::text_edit::CCursorRange; pub use epaint::text::{ - FontData, FontDefinitions, FontFamily, Fonts, Galley, LayoutJob, LayoutSection, TextFormat, - TAB_SIZE, + cursor::CCursor, FontData, FontDefinitions, FontFamily, Fonts, Galley, LayoutJob, + LayoutSection, TextFormat, TAB_SIZE, }; } diff --git a/egui_demo_lib/src/apps/demo/text_edit.rs b/egui_demo_lib/src/apps/demo/text_edit.rs index b294115b245..e62dd17bcfc 100644 --- a/egui_demo_lib/src/apps/demo/text_edit.rs +++ b/egui_demo_lib/src/apps/demo/text_edit.rs @@ -64,6 +64,7 @@ impl super::View for TextEdit { anything_selected, egui::Label::new("Press ctrl+T to toggle the case of selected text (cmd+T on Mac)"), ); + if ui .input_mut() .consume_key(egui::Modifiers::COMMAND, egui::Key::T) @@ -82,5 +83,29 @@ impl super::View for TextEdit { text.insert_text(&new_text, selected_chars.start); } } + + ui.horizontal(|ui| { + ui.label("Move cursor to the:"); + + if ui.button("start").clicked() { + let text_edit_id = output.response.id; + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), text_edit_id) { + let ccursor = egui::text::CCursor::new(0); + state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor))); + state.store(ui.ctx(), text_edit_id); + ui.ctx().memory().request_focus(text_edit_id); // give focus back to the `TextEdit`. + } + } + + if ui.button("end").clicked() { + let text_edit_id = output.response.id; + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), text_edit_id) { + let ccursor = egui::text::CCursor::new(text.chars().count()); + state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor))); + state.store(ui.ctx(), text_edit_id); + ui.ctx().memory().request_focus(text_edit_id); // give focus back to the `TextEdit`. + } + } + }); } }