Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DragValue: update value on each key press by default #2880

Merged
merged 4 commits into from
Aug 9, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions crates/egui/src/widgets/drag_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub struct DragValue<'a> {
max_decimals: Option<usize>,
custom_formatter: Option<NumFormatter<'a>>,
custom_parser: Option<NumParser<'a>>,
update_while_editing: bool,
}

impl<'a> DragValue<'a> {
Expand Down Expand Up @@ -94,6 +95,7 @@ impl<'a> DragValue<'a> {
max_decimals: None,
custom_formatter: None,
custom_parser: None,
update_while_editing: true,
}
}

Expand Down Expand Up @@ -352,6 +354,12 @@ impl<'a> DragValue<'a> {
}
.custom_parser(|s| i64::from_str_radix(s, 16).map(|n| n as f64).ok())
}

/// Update the value when there are changes while editing. (Default: true)
emilk marked this conversation as resolved.
Show resolved Hide resolved
pub fn update_while_editing(mut self, update: bool) -> Self {
self.update_while_editing = update;
self
}
}

impl<'a> Widget for DragValue<'a> {
Expand All @@ -366,6 +374,7 @@ impl<'a> Widget for DragValue<'a> {
max_decimals,
custom_formatter,
custom_parser,
update_while_editing,
} = self;

let shift = ui.input(|i| i.modifiers.shift_only());
Expand Down Expand Up @@ -475,9 +484,15 @@ impl<'a> Widget for DragValue<'a> {
.desired_width(ui.spacing().interact_size.x)
.font(text_style),
);
// Only update the value when the user presses enter, or clicks elsewhere. NOT every frame.
// See https://github.com/emilk/egui/issues/2687
if response.lost_focus() {

let update = if update_while_editing {
// Update when the edit content has changed.
response.changed()
} else {
// Update only when the edit has lost focus.
response.lost_focus()
};
if update {
let parsed_value = match custom_parser {
Some(parser) => parser(&value_text),
None => value_text.parse().ok(),
Expand Down