I'm working on a project in C using gtk+ 2.0.
I must check if the user has pressed left click on a image. I thought to call a function when left click is pressed and to get the position of the mouse, but how can I do that?
I hope I can assume you know how to connect an event to a widget, but if not: Here's a previous answer of mine that demonstrates how to do just that.
g_signal_connect for right mouse click?
As you can see there the event is passed as a GdkEventButton *
(event
from now on). This struct has the member fields that you are after: event->x
and event->y
both are gdouble
fields.
Anyway, @unwind is right. As the GTK docs clearly state:
GtkImage is a “no window” widget (has no GdkWindow of its own), so by default does not receive events. If you want to receive events on the image, such as button clicks, place the image inside a GtkEventBox, then connect to the event signals on the event box.
GtkImage
is not the only "windowless" widget, BTW. GtkLabel
, for example, requires a similar approach if you want to handle clicks on a label. Anyway: More info here.
The man page then continues with a full code example of how to handle clicks on a GtkImage
widget. Just look for the title "Handling button press events on a GtkImage." for the full explanation, but here's the code in case the link breaks:
static gboolean
button_press_callback (GtkWidget *event_box,
GdkEventButton *event,
gpointer data)
{
g_print ("Event box clicked at coordinates %f,%f\n",
event->x, event->y);
// Returning TRUE means we handled the event, so the signal
// emission should be stopped (don’t call any further callbacks
// that may be connected). Return FALSE to continue invoking callbacks.
return TRUE;
}
static GtkWidget*
create_image (void)
{
GtkWidget *image;
GtkWidget *event_box;
image = gtk_image_new_from_file ("myfile.png");
event_box = gtk_event_box_new ();
gtk_container_add (GTK_CONTAINER (event_box), image);
g_signal_connect (G_OBJECT (event_box),
"button_press_event",
G_CALLBACK (button_press_callback),
image);
return image;
}
The problem is that the GtkImage widget which is used to show an image in GTK+ does not generate events.
It's a "nowindow" widget, meaning that it's a passive container, which is used to display information and not to interact with the user.
You can fix that by wrapping the image in a GtkEventBox, which will add event support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With