Search code examples
cmouseeventgtk3cairo

How to handle mouse motion events in GTK3?


I am trying to implement the following feature using C/GTK3/Cairo:

-Left click on an GtkDrawingArea Widget and printf the coordinates Xo and Yo.

-While keeping the left button down, move the mouse and draw a line conecting (Xo,Yo) to the current mouse position.

-Release the left mouse button and printf("something")

How do I do this? Anyone knows of a good tutorial showing how to handle mouse clicl-move events?

So far, the best I found was this zetcode lines (which shows how to handle mouse click events but not button-down/move/button-up and this , which explains how to change the mouse cursor when hovering over a Widget.

Thanks


Solution

  • Did you see this GtkDrawingArea demo from the Gtk people? This one is written in C, but there is a Python version of the same program (links updated - thanks @kyuuhachi).

    Anyway, in the constructor (__init__), calls are connected to the motion_notify_event.

    You also need to connect to the button_press_event and the button_release_event.

    Then, on button press, you save the coordinates of the start point. (and save it to the end point too, which are the same for now).

    On each motion_notify_event, you delete the previous line (by overwriting), and redraw it to the new end point.

    Finally, when the button is released, the line is final.

    It's much easier if you use a canvas widget, for example GooCanvas, which takes care of most of the updating. You can just update the coordinates of the line object, and it will move itself. Also you can easily remove lines. The 'algorithm' is similar as above:

    • Connect button_press_event, button_release_event, and motion_notifyevent to the canvas,
    • When a button press occurs, create a GooCanvas.polyline object, and set begin and endpoint,
    • Update the endpoint on each motion_notify_event
    • Finalize with a button_release_event.