Skip to content

Commit

Permalink
Add example of how to move text cursor in a TextEdit
Browse files Browse the repository at this point in the history
  • Loading branch information
emilk committed Mar 20, 2022
1 parent fde9c23 commit ccbddcf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
5 changes: 3 additions & 2 deletions egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}

Expand Down
25 changes: 25 additions & 0 deletions egui_demo_lib/src/apps/demo/text_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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`.
}
}
});
}
}

0 comments on commit ccbddcf

Please sign in to comment.