Skip to main content

DragValue

Struct DragValue 

Source
pub struct DragValue<'a> { /* private fields */ }
Available on crate feature egui only.
Expand description

A numeric value that you can change by dragging the number. More compact than a crate::Slider.

ui.add(egui::DragValue::new(&mut my_f32).speed(0.1));

Implementations§

Source§

impl<'a> DragValue<'a>

Source

pub const CLASS: ClassName

Present on the Button and the TextEdit a drag value is built from.

Source

pub fn new<Num>(value: &'a mut Num) -> DragValue<'a>
where Num: Numeric,

Creates a drag value for value.

Integer types get a step of one, a speed of a quarter per point, and their full range.

Source

pub fn from_get_set( get_set_value: impl FnMut(Option<f64>) -> f64 + 'a, ) -> DragValue<'a>

Creates a drag value over a value that cannot be borrowed directly.

The closure is called with None to read the value and with Some(new_value) to write it, and returns the value either way.

Source

pub fn min_size(self, min_size: Vec2) -> DragValue<'a>

The minimum size of the drag value, in both its dragged and its text-edited state.

Defaults to crate::style::Spacing::interact_size.

Source

pub fn speed(self, speed: impl Into<f64>) -> DragValue<'a>

How much the value changes when dragged one point (logical pixel).

Should be finite and greater than zero.

Source

pub fn range<Num>(self, range: RangeInclusive<Num>) -> DragValue<'a>
where Num: Numeric,

Sets valid range for dragging the value.

By default all values are clamped to this range, even when not interacted with. You can change this behavior by passing false to Self::clamp_existing_to_range.

Source

pub fn clamp_existing_to_range( self, clamp_existing_to_range: bool, ) -> DragValue<'a>

If set to true, existing values will be clamped to Self::range.

If false, only values entered by the user (via dragging or text editing) will be clamped to the range.

§Without calling range
let mut my_value: f32 = 1337.0;
ui.add(egui::DragValue::new(&mut my_value));
assert_eq!(my_value, 1337.0, "No range, no clamp");
§With .clamp_existing_to_range(true) (default)
let mut my_value: f32 = 1337.0;
ui.add(egui::DragValue::new(&mut my_value).range(0.0..=1.0));
assert!(0.0 <= my_value && my_value <= 1.0, "Existing values should be clamped");
§With .clamp_existing_to_range(false)
let mut my_value: f32 = 1337.0;
let response = ui.add(
    egui::DragValue::new(&mut my_value).range(0.0..=1.0)
        .clamp_existing_to_range(false)
);
if response.dragged() {
    // The user edited the value, so it should be clamped to the range
    assert!(0.0 <= my_value && my_value <= 1.0);
} else {
    // The user didn't edit, so our original value should still be here:
    assert_eq!(my_value, 1337.0);
}
Source

pub fn format(self, format: ValueFormat<'a>) -> DragValue<'a>

Replace how the number is written and read back.

Source

pub fn prefix(self, prefix: impl IntoAtoms<'a>) -> DragValue<'a>

Show a prefix before the number, e.g. “x: “.

Goes in front of any prefix already set, so .prefix("b").prefix("a") shows ab.

Source

pub fn suffix(self, suffix: impl IntoAtoms<'a>) -> DragValue<'a>

Add a suffix to the number, this can be e.g. a unit (“°” or “ m“).

Goes after any suffix already set, so .suffix("a").suffix("b") shows ab.

Source

pub fn min_decimals(self, min_decimals: usize) -> DragValue<'a>

Set a minimum number of decimals to display. Normally you don’t need to pick a precision, as the slider will intelligently pick a precision for you. Regardless of precision the slider will use “smart aim” to help the user select nice, round values.

Source

pub fn max_decimals(self, max_decimals: usize) -> DragValue<'a>

Set a maximum number of decimals to display. Values will also be rounded to this number of decimals. Normally you don’t need to pick a precision, as the slider will intelligently pick a precision for you. Regardless of precision the slider will use “smart aim” to help the user select nice, round values.

Source

pub fn max_decimals_opt(self, max_decimals: Option<usize>) -> DragValue<'a>

Set the maximum number of decimals to display, or None to let the widget pick.

Values will also be rounded to this number of decimals when it is set.

Source

pub fn fixed_decimals(self, num_decimals: usize) -> DragValue<'a>

Set an exact number of decimals to display. Values will also be rounded to this number of decimals. Normally you don’t need to pick a precision, as the slider will intelligently pick a precision for you. Regardless of precision the slider will use “smart aim” to help the user select nice, round values.

Source

pub fn custom_formatter( self, formatter: impl Fn(f64, RangeInclusive<usize>) -> String + 'a, ) -> DragValue<'a>

Set custom formatter defining how numbers are converted into text.

A custom formatter takes a f64 for the numeric value and a RangeInclusive<usize> representing the decimal range i.e. minimum and maximum number of decimal places shown.

The default formatter is crate::Style::number_formatter.

See also: DragValue::custom_parser

ui.add(egui::DragValue::new(&mut my_i32)
    .range(0..=((60 * 60 * 24) - 1))
    .custom_formatter(|n, _| {
        let n = n as i32;
        let hours = n / (60 * 60);
        let mins = (n / 60) % 60;
        let secs = n % 60;
        format!("{hours:02}:{mins:02}:{secs:02}")
    })
    .custom_parser(|s| {
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() == 3 {
            parts[0].parse::<i32>().and_then(|h| {
                parts[1].parse::<i32>().and_then(|m| {
                    parts[2].parse::<i32>().map(|s| {
                        ((h * 60 * 60) + (m * 60) + s) as f64
                    })
                })
            })
            .ok()
        } else {
            None
        }
    }));
Source

pub fn custom_parser( self, parser: impl Fn(&str) -> Option<f64> + 'a, ) -> DragValue<'a>

Set custom parser defining how the text input is parsed into a number.

A custom parser takes an &str to parse into a number and returns a f64 if it was successfully parsed or None otherwise.

See also: DragValue::custom_formatter

ui.add(egui::DragValue::new(&mut my_i32)
    .range(0..=((60 * 60 * 24) - 1))
    .custom_formatter(|n, _| {
        let n = n as i32;
        let hours = n / (60 * 60);
        let mins = (n / 60) % 60;
        let secs = n % 60;
        format!("{hours:02}:{mins:02}:{secs:02}")
    })
    .custom_parser(|s| {
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() == 3 {
            parts[0].parse::<i32>().and_then(|h| {
                parts[1].parse::<i32>().and_then(|m| {
                    parts[2].parse::<i32>().map(|s| {
                        ((h * 60 * 60) + (m * 60) + s) as f64
                    })
                })
            })
            .ok()
        } else {
            None
        }
    }));
Source

pub fn binary(self, min_width: usize, twos_complement: bool) -> DragValue<'a>

Display and parse the number as a binary integer. See ValueFormat::binary.

ui.add(egui::DragValue::new(&mut my_i32).binary(64, false));
Source

pub fn octal(self, min_width: usize, twos_complement: bool) -> DragValue<'a>

Display and parse the number as an octal integer. See ValueFormat::octal.

ui.add(egui::DragValue::new(&mut my_i32).octal(22, false));
Source

pub fn hexadecimal( self, min_width: usize, twos_complement: bool, upper: bool, ) -> DragValue<'a>

Display and parse the number as a hexadecimal integer. See ValueFormat::hexadecimal.

ui.add(egui::DragValue::new(&mut my_i32).hexadecimal(16, false, true));
Source

pub fn update_while_editing(self, update: bool) -> DragValue<'a>

Update the value on each key press when text-editing the value.

Default: true. If false, the value will only be updated when user presses enter or deselects the value.

Source

pub fn clip_text(self, clip_text: bool) -> DragValue<'a>

Keep the value inside the widget’s width when text-editing it.

Default: false, which lets the widget widen to fit whatever has been typed, carrying the surrounding layout with it. When true the widget holds its width and the text scrolls inside it, following the cursor.

Source

pub fn atoms(&self) -> Atoms<'a>

The Atoms of the drag value: its prefix, a placeholder for the number, and its suffix.

This includes any images you have on the DragValue.

Trait Implementations§

Source§

impl HasClasses for DragValue<'_>

Source§

fn classes(&self) -> &Classes

Source§

fn classes_mut(&mut self) -> &mut Classes

Source§

fn has_class(&self, class: &str) -> bool

True if the class is present.
Source§

fn add_class(&mut self, class: impl Into<ClassName>) -> &mut Self
where Self: Sized,

Add the given class in-place.
Source§

fn set_class(&mut self, class: impl Into<ClassName>, present: bool) -> &mut Self
where Self: Sized,

Add the given class in-place if present, remove it otherwise. Read more
Source§

fn remove_class(&mut self, class: impl Into<ClassName>) -> &mut Self
where Self: Sized,

Remove the given class in-place.
Source§

fn with_class(self, class: impl Into<ClassName>) -> Self
where Self: Sized,

Add the given class by consuming self.
Source§

fn add_classes(&mut self, classes: Classes) -> &mut Self

Append all the given classes at the end, deduplicating them.
Source§

fn with_classes(self, classes: Classes) -> Self
where Self: Sized,

Append all the given classes at the end, deduplicating them. Consuming self.
Source§

fn add_class_if( &mut self, class: impl Into<ClassName>, condition: bool, ) -> &mut Self
where Self: Sized,

Add a class to the list if the condition is true. Read more
Source§

fn with_class_if(self, class: impl Into<ClassName>, condition: bool) -> Self
where Self: Sized,

Add the given class by consuming self if the condition is true. Read more
Source§

fn iter_classes(&self) -> Iter<'_, ClassName> ⓘ

Iterate over the classes, in the order they were added.
Source§

fn classes_as_slice(&self) -> &[ClassName]

Return the classes as a slice.
Source§

impl Widget for DragValue<'_>

Source§

fn ui(self, ui: &mut Ui) -> Response

Allocate space, interact, paint, and return a Response. Read more
Source§

fn boxed<'a>(self) -> Box<dyn FnOnce(&mut Ui) -> Response + 'a>
where Self: Sized + 'a,

Box this widget for dynamic dispatch.

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for DragValue<'a>

§

impl<'a> !Send for DragValue<'a>

§

impl<'a> !Sync for DragValue<'a>

§

impl<'a> !UnwindSafe for DragValue<'a>

§

impl<'a> Forget for DragValue<'a>

§

impl<'a> Freeze for DragValue<'a>
where *const dyn FnMut(Option<f64>) -> f64 + 'a is !null: Freeze, PhantomData<dyn FnMut(Option<f64>) -> f64 + 'a>: Freeze, *const u8 is !null: Freeze, PhantomData<Atom<'a>>: Freeze, *const ArcInner<dyn Fn(f64, RangeInclusive<usize>) -> String + 'a> is !null: Freeze, PhantomData<ArcInner<dyn Fn(f64, RangeInclusive<usize>) -> String + 'a>>: Freeze, *const ArcInner<dyn Fn(&str) -> Option<f64> + 'a> is !null: Freeze, PhantomData<ArcInner<dyn Fn(&str) -> Option<f64> + 'a>>: Freeze, &'static str: Freeze, *const ArcInner<str> is !null: Freeze, PhantomData<ArcInner<str>>: Freeze, *const ClassName is !null: Freeze, PhantomData<ClassName>: Freeze,

§

impl<'a> Move for DragValue<'a>

§

impl<'a> Unpin for DragValue<'a>
where Box<dyn FnMut(Option<f64>) -> f64 + 'a>: Unpin, *const u8 is !null: Unpin, NonZero<u64>: Unpin, Arc<RichText>: Unpin, Arc<LayoutJob>: Unpin, Arc<Galley>: Unpin, &'a str: Unpin, String: Unpin, &'static str: Unpin, &'static [u8]: Unpin, Arc<[u8]>: Unpin, Box<dyn FnOnce(&Ui, IntoSizedArgs) -> IntoSizedResult<'static> + 'a>: Unpin, Arc<dyn Fn(&Ui, AtomPaintArgs) + 'a>: Unpin, Box<WidgetAtom<'a>>: Unpin, Box<ContainerAtom<'a>>: Unpin, Arc<dyn Fn(f64, RangeInclusive<usize>) -> String + 'a>: Unpin, Arc<dyn Fn(&str) -> Option<f64> + 'a>: Unpin, Arc<str>: Unpin, *const ClassName is !null: Unpin, ClassName: Unpin,

§

impl<'a> UnsafeUnpin for DragValue<'a>
where *const dyn FnMut(Option<f64>) -> f64 + 'a is !null: UnsafeUnpin, PhantomData<dyn FnMut(Option<f64>) -> f64 + 'a>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<Atom<'a>>: UnsafeUnpin, *const ArcInner<dyn Fn(f64, RangeInclusive<usize>) -> String + 'a> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Fn(f64, RangeInclusive<usize>) -> String + 'a>>: UnsafeUnpin, *const ArcInner<dyn Fn(&str) -> Option<f64> + 'a> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Fn(&str) -> Option<f64> + 'a>>: UnsafeUnpin, &'static str: UnsafeUnpin, *const ArcInner<str> is !null: UnsafeUnpin, PhantomData<ArcInner<str>>: UnsafeUnpin, *const ClassName is !null: UnsafeUnpin, PhantomData<ClassName>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

Source§

fn simd_from(_simd: S, value: T) -> T

Source§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

Source§

fn simd_into(self, simd: S) -> T

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more