Skip to main content

Button

Struct Button 

Source
pub struct Button { /* private fields */ }
Expand description

An element that creates a button with a label and optional icons.

Common buttons:

To create a more complex button than what the Button or IconButton components provide, use ButtonLike directly.

§Examples

A button with a label, is typically used in scenarios such as a form, where the button’s label indicates what action will be performed when the button is clicked.

use ui::prelude::*;

Button::new("button_id", "Click me!")
    .on_click(|event, window, cx| {
        // Handle click event
    });

A toggleable button, is typically used in scenarios such as a toolbar, where the button’s state indicates whether a feature is enabled or not, or a trigger for a popover menu, where clicking the button toggles the visibility of the menu.

use ui::prelude::*;

Button::new("button_id", "Click me!")
    .start_icon(Icon::new(IconName::Check))
    .toggle_state(true)
    .on_click(|event, window, cx| {
        // Handle click event
    });

To change the style of the button when it is selected use the selected_style method.

use ui::prelude::*;
use ui::TintColor;

Button::new("button_id", "Click me!")
    .toggle_state(true)
    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
    .on_click(|event, window, cx| {
        // Handle click event
    });

This will create a button with a blue tinted background when selected.

A full-width button, is typically used in scenarios such as the bottom of a modal or form, where it occupies the entire width of its container. The button’s content, including text and icons, is centered by default.

use ui::prelude::*;

let button = Button::new("button_id", "Click me!")
    .full_width()
    .on_click(|event, window, cx| {
        // Handle click event
    });

Implementations§

Source§

impl Button

Source

pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self

Creates a new Button with a specified identifier and label.

This is the primary constructor for a Button component. It initializes the button with the provided identifier and label text, setting all other properties to their default values, which can be customized using the builder pattern methods provided by this struct.

Source

pub fn color(self, label_color: impl Into<Option<Color>>) -> Self

Sets the color of the button’s label.

Source

pub fn label_size(self, label_size: impl Into<Option<LabelSize>>) -> Self

Defines the size of the button’s label.

Source

pub fn selected_label<L: Into<SharedString>>( self, label: impl Into<Option<L>>, ) -> Self

Sets the label used when the button is in a selected state.

Source

pub fn selected_label_color(self, color: impl Into<Option<Color>>) -> Self

Sets the label color used when the button is in a selected state.

Source

pub fn start_icon(self, icon: impl Into<Option<Icon>>) -> Self

Sets an icon to display at the start (left) of the button label.

The icon’s color will be overridden to Color::Disabled when the button is disabled.

Source

pub fn end_icon(self, icon: impl Into<Option<Icon>>) -> Self

Sets an icon to display at the end (right) of the button label.

The icon’s color will be overridden to Color::Disabled when the button is disabled.

Source

pub fn key_binding(self, key_binding: impl Into<Option<KeyBinding>>) -> Self

Display the keybinding that triggers the button action.

Source

pub fn key_binding_position(self, position: KeybindingPosition) -> Self

Sets the position of the keybinding relative to the button label.

This method allows you to specify where the keybinding should be displayed in relation to the button’s label.

Source

pub fn alpha(self, alpha: f32) -> Self

Sets the alpha property of the color of label.

Source

pub fn truncate(self, truncate: bool) -> Self

Truncates overflowing labels with an ellipsis () if needed.

Buttons with static labels should never be truncated, ensure this is only used when the label is dynamic and may overflow.

Source

pub fn loading(self, loading: bool) -> Self

Displays a rotating loading spinner in place of the start_icon.

When loading is true, any start_icon is ignored. and a rotating

Source

pub fn primary(self) -> Self

Convenience for a Tailwind-style solid “primary” button: solid palette::primary(600) background with white text.

Equivalent to .style(ButtonStyle::Tinted(TintColor::Accent)).

Source

pub fn danger(self) -> Self

Convenience for a Tailwind-style solid “danger” button: solid palette::danger(600) background with white text.

Equivalent to .style(ButtonStyle::Tinted(TintColor::Error)).

Source

pub fn soft(self) -> Self

Convenience for a Tailwind-style “soft” button: faint palette::primary(50) background with palette::primary(700) text.

Implemented as an additive background override on top of the Tinted(Accent) style, so it does not require a new ButtonStyle variant.

Source

pub fn variant(self, variant: ButtonVariant) -> Self

shadcn/ui variant alias (recommended vocabulary).

Maps to existing ButtonStyle / convenience builders without renaming legacy .primary() / .danger() / .soft() call sites. For link-style buttons use [ButtonLink] instead.

Source

pub fn shadcn_size(self, size: ButtonSizeAlias) -> Self

shadcn/ui size alias. Icon-only sizing uses IconButton, not this API.

Trait Implementations§

Source§

impl ButtonCommon for Button

Source§

fn style(self, style: ButtonStyle) -> Self

Sets the visual style of the button.

Source§

fn size(self, size: ButtonSize) -> Self

Sets the size of the button.

Source§

fn tooltip( self, tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static, ) -> Self

Sets a tooltip that appears on hover.

§Examples

Add a tooltip to a button:

use ui::{Tooltip, prelude::*};

Button::new("tooltip_button", "Hover Me")
    .tooltip(Tooltip::text("This is a tooltip"));
Source§

fn id(&self) -> &ElementId

A unique element ID to identify the button.
Source§

fn tab_index(self, tab_index: impl Into<isize>) -> Self

Source§

fn layer(self, elevation: ElevationIndex) -> Self

Source§

fn track_focus(self, focus_handle: &FocusHandle) -> Self

Source§

impl Clickable for Button

Source§

fn on_click( self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self

Sets the click handler that will fire whenever the element is clicked.
Source§

fn cursor_style(self, cursor_style: CursorStyle) -> Self

Sets the cursor style when hovering over the element.
Source§

impl Component for Button

Source§

fn scope() -> ComponentScope

Returns the scope of the component. Read more
Source§

fn sort_name() -> &'static str

Returns a name that the component should be sorted by. Read more
Source§

fn description() -> Option<&'static str>

An optional description of the component. Read more
Source§

fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement>

The component’s preview. Read more
Source§

fn id() -> ComponentId

The component’s unique identifier. Read more
Source§

fn status() -> ComponentStatus

The ready status of this component. Read more
Source§

fn name() -> &'static str

The name of the component. Read more
Source§

impl Disableable for Button

Source§

fn disabled(self, disabled: bool) -> Self

Disables the button, preventing interaction and changing its appearance.

When disabled, the button’s icon and label will use Color::Disabled.

§Examples

Create a disabled button:

use ui::prelude::*;

Button::new("disabled_button", "Can't Click Me")
    .disabled(true);
Source§

impl Documented for Button

Source§

const DOCS: &'static str = "An element that creates a button with a label and optional icons.\n\nCommon buttons:\n- Label, Icon + Label: [`Button`] (this component)\n- Icon only: [`IconButton`]\n- Custom: [`ButtonLike`]\n\nTo create a more complex button than what the [`Button`] or [`IconButton`] components provide, use\n[`ButtonLike`] directly.\n\n# Examples\n\n**A button with a label**, is typically used in scenarios such as a form, where the button\'s label\nindicates what action will be performed when the button is clicked.\n\n```\nuse ui::prelude::*;\n\nButton::new(\"button_id\", \"Click me!\")\n.on_click(|event, window, cx| {\n// Handle click event\n});\n```\n\n**A toggleable button**, is typically used in scenarios such as a toolbar,\nwhere the button\'s state indicates whether a feature is enabled or not, or\na trigger for a popover menu, where clicking the button toggles the visibility of the menu.\n\n```\nuse ui::prelude::*;\n\nButton::new(\"button_id\", \"Click me!\")\n.start_icon(Icon::new(IconName::Check))\n.toggle_state(true)\n.on_click(|event, window, cx| {\n// Handle click event\n});\n```\n\nTo change the style of the button when it is selected use the [`selected_style`][Button::selected_style] method.\n\n```\nuse ui::prelude::*;\nuse ui::TintColor;\n\nButton::new(\"button_id\", \"Click me!\")\n.toggle_state(true)\n.selected_style(ButtonStyle::Tinted(TintColor::Accent))\n.on_click(|event, window, cx| {\n// Handle click event\n});\n```\nThis will create a button with a blue tinted background when selected.\n\n**A full-width button**, is typically used in scenarios such as the bottom of a modal or form, where it occupies the entire width of its container.\nThe button\'s content, including text and icons, is centered by default.\n\n```\nuse ui::prelude::*;\n\nlet button = Button::new(\"button_id\", \"Click me!\")\n.full_width()\n.on_click(|event, window, cx| {\n// Handle click event\n});\n```\n"

The static doc comments on this type.
Source§

impl FixedWidth for Button

Source§

fn width(self, width: impl Into<DefiniteLength>) -> Self

Sets a fixed width for the button.

§Examples

Create a button with a fixed width of 100 pixels:

use ui::prelude::*;

Button::new("fixed_width_button", "Fixed Width")
    .width(px(100.0));
Source§

fn full_width(self) -> Self

Makes the button take up the full width of its container.

§Examples

Create a button that takes up the full width of its container:

use ui::prelude::*;

Button::new("full_width_button", "Full Width")
    .full_width();
Source§

impl IntoElement for Button

Source§

type Element = Component<Button>

The specific type of element into which the implementing type is converted. Useful for converting other types into elements automatically, like Strings
Source§

fn into_element(self) -> Self::Element

Convert self into a type that implements Element.
Source§

fn into_any_element(self) -> AnyElement

Convert self into a dynamically-typed AnyElement.
Source§

impl RenderOnce for Button

Source§

fn render(self, _window: &mut Window, cx: &mut App) -> ButtonLike

Render this component into an element tree. Note that this method takes ownership of self, as compared to Render::render() method which takes a mutable reference.
Source§

impl SelectableButton for Button

Source§

fn selected_style(self, style: ButtonStyle) -> Self

Sets the style for the button in a selected state.

§Examples

Customize the selected appearance of a button:

use ui::prelude::*;
use ui::TintColor;

Button::new("styled_button", "Styled Button")
    .toggle_state(true)
    .selected_style(ButtonStyle::Tinted(TintColor::Accent));
Source§

impl Toggleable for Button

Source§

fn toggle_state(self, selected: bool) -> Self

Sets the selected state of the button.

§Examples

Create a toggleable button that changes appearance when selected:

use ui::prelude::*;
use ui::TintColor;

let selected = true;

Button::new("toggle_button", "Toggle Me")
    .start_icon(Icon::new(IconName::Check))
    .toggle_state(selected)
    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
    .on_click(|event, window, cx| {
        // Toggle the selected state
    });

Auto Trait Implementations§

§

impl !RefUnwindSafe for Button

§

impl !Send for Button

§

impl !Sync for Button

§

impl !UnwindSafe for Button

§

impl Freeze for Button

§

impl Unpin for Button

§

impl UnsafeUnpin for Button

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
Source§

impl<E> AnimationExt for E
where E: IntoElement + 'static,

Source§

fn with_animation( self, id: impl Into<ElementId>, animation: Animation, animator: impl Fn(Self, f32) -> Self + 'static, ) -> AnimationElement<Self>
where Self: Sized,

Render this component or element with an animation
Source§

fn with_animations( self, id: impl Into<ElementId>, animations: Vec<Animation>, animator: impl Fn(Self, usize, f32) -> Self + 'static, ) -> AnimationElement<Self>
where Self: Sized,

Render this component or element with a chain of animations
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, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
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<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
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> CommonAnimationExt for T
where T: AnimationExt,

Source§

fn with_rotate_animation(self, duration: u64) -> AnimationElement<Self>
where Self: Transformable + Sized,

Render this component as rotating over the given duration. Read more
Source§

fn with_keyed_rotate_animation( self, id: impl Into<ElementId>, duration: u64, ) -> AnimationElement<Self>
where Self: Transformable + Sized,

Render this component as rotating with the given element ID over the given duration.
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T> FluentBuilder for T
where T: IntoElement,

Source§

fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
where Self: Sized,

Imperatively modify self with the given closure.
Source§

fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
where Self: Sized,

Conditionally modify self with the given closure.
Source§

fn when_else( self, condition: bool, then: impl FnOnce(Self) -> Self, else_fn: impl FnOnce(Self) -> Self, ) -> Self
where Self: Sized,

Conditionally modify self with the given closure.
Source§

fn when_some<T>( self, option: Option<T>, then: impl FnOnce(Self, T) -> Self, ) -> Self
where Self: Sized,

Conditionally unwrap and modify self with the given closure, if the given option is Some.
Source§

fn when_none<T>( self, option: &Option<T>, then: impl FnOnce(Self) -> Self, ) -> Self
where Self: Sized,

Conditionally unwrap and modify self with the given closure, if the given option is None.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
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, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
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> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PopoverTrigger for T
where T: IntoElement + Clickable + Toggleable + 'static,

Source§

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

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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