3

In GTK+3, how do I get a drawing_area to respond to mouse events?

In main() function I declared my drawing_area:

GtkWidget *drawing_area;

Then I connected the drawing_area with the mouse click signal:

g_signal_connect(drawing_area, "button-press-event", G_CALLBACK(clicked), NULL);

the function "clicked" is defined by:

static gboolean clicked(GtkWidget *widget, GdkEventButton *event, gpointer user_data)

    printf("Clicked! \n");

    return TRUE;
}

The program runs and shows the drawing_area but when I click on it, no answer, nothing happens! Why is this happening?

4

2 回答 2

4

It seems that GtkDrawingArea can not receive mouse events by default

Take a look to the documentation:

To receive mouse events on a drawing area, you will need to enable them with gtk_widget_add_events(). To receive keyboard events, you will need to set the “can-focus” property on the drawing area, and you should probably draw some user-visible indication that the drawing area is focused. Use gtk_widget_has_focus() in your expose event handler to decide whether to draw the focus indicator. See gtk_render_focus() for one way to draw focus.

Or try connecting the event "button-press-event" to the window:

g_signal_connect(window, "button-press-event", G_CALLBACK(clicked), NULL);

instead of

g_signal_connect(drawing_area, "button-press-event", G_CALLBACK(clicked), NULL);

As in this example:

http://zetcode.com/gfx/cairo/basicdrawing/

于 2017-05-19T19:33:13.470 回答
1

A complete example is: https://developer.gnome.org/gtk3/stable/ch01s05.html
This link has moved (thanks TrentP). The new link is: https://docs.gtk.org/gtk4/getting_started.html#custom-drawing

It demonstrates input event handling by means of ::button-press and ::motion-notify handlers.

于 2018-10-08T19:16:50.963 回答