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::{widget::mouse_area, Sandbox, Settings};
fn main() -> iced::Result {
MyApp::run(Settings::default())
}
#[derive(Debug, Clone)]
enum MyAppMessage {
Pressed,
Released,
}
struct MyApp {
state: String,
}
impl Sandbox for MyApp {
type Message = MyAppMessage;
fn new() -> Self {
Self {
state: "Start".into(),
}
}
fn title(&self) -> String {
String::from("My App")
}
fn update(&mut self, message: Self::Message) {
match message {
MyAppMessage::Pressed => self.state = "Pressed".into(),
MyAppMessage::Released => self.state = "Released".into(),
}
}
fn view(&self) -> iced::Element<Self::Message> {
mouse_area(self.state.as_str())
.on_press(MyAppMessage::Pressed)
.on_release(MyAppMessage::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