Libove Blog

Personal Blog about anything - mostly programming, cooking and random thoughts

Rust GTK4 - Mouse Events in DrawingArea

For the app I'm currently working on I need to react to mouse inputs in a drawing area. I need the position of the mouse and the possibility to react to mouse clicks.

Mouse Position

The mouse position can be obtained by using an EventControllerMotion. This is added to the DrawingArea.

let pos_controller = EventControllerMotion::new();
pos_controller.connect_motion(move |_con, x, y| {
    ...
});
drawing_area.add_controller(pos_controller);

Mouse Clicks

For each mouse button you want to "observe" a GestureClick is created and added to the DrawingArea.

let gesture_click = GestureClick::builder()
    .button(GDK_BUTTON_PRIMARY as u32)
    .build();

gesture_click.connect_pressed(move |_, _, _, _| {
    // create to mouse click
});
drawing_area.add_controller(gesture_click);