If we only consider mouse pressed or released events, we can use MouseArea. The MouseArea gives the widget being put in it the sense of mouse pressed/released events, even if the widget has no build-in support of the events. For example, we can make a Text to respond to mouse pressed/released events.
use iced::{Task, widget::mouse_area};
fn main() -> iced::Result {
iced::application("My App", MyApp::update, MyApp::view).run_with(MyApp::new)
}
#[derive(Debug, Clone)]
enum Message {
Pressed,
Released,
}
#[derive(Default)]
struct MyApp {
state: String,
}
impl MyApp {
fn new() -> (Self, Task<Message>) {
(
Self {
state: "Start".into(),
},
Task::none(),
)
}
fn update(&mut self, message: Message) {
match message {
Message::Pressed => self.state = "Pressed".into(),
Message::Released => self.state = "Released".into(),
}
}
fn view(&self) -> iced::Element<Message> {
mouse_area(self.state.as_str())
.on_press(Message::Pressed)
.on_release(Message::Released)
.into()
}
}In addition to on_press and on_release methods, MouseArea also supports on_middle_press, on_right_press, etc.
When the mouse is pressed:
And when the mouse is released:
➡️ Next: Producing Messages By Mouse Events
📘 Back: Table of contents

