1

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

Community
  • 1
  • 1
PintoDoido
  • 1,011
  • 16
  • 35
  • 1
    With the first link you should be able to implement your steps 1 and 3. If that is not sufficient, please provide [MCVE](http://stackoverflow.com/help/mcve) that shows your problem. – Gerhardh May 03 '17 at 15:29
  • 1
    For step 2 you need to save where you pressed the button and then handle `"motion-notify-event"` for any movement of the mouse. – Gerhardh May 03 '17 at 15:31

1 Answers1

2

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.
jcoppens
  • 5,306
  • 6
  • 27
  • 47
  • Both links are dead. Please fix. – Matthias Urlichs Jan 02 '22 at 14:50
  • 1
    I think the correct links are [C](https://gitlab.gnome.org/GNOME/gtk/-/blob/main/demos/gtk-demo/drawingarea.c) and [Python](https://gitlab.gnome.org/GNOME/pygobject/-/blob/master/examples/demo/demos/drawingarea.py). Says the edit queue is full if I try to edit, so I'll just put a comment. – Kyuuhachi Aug 24 '22 at 08:29
  • Thanks for the update, @Kyuuhachi! I'll update the addresses above. – jcoppens Aug 24 '22 at 12:08