Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect mouse click over an image in GTK+?

Tags:

c

mouse

gtk

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?

like image 662
Alin Enachescu Avatar asked Jun 24 '14 12:06

Alin Enachescu


2 Answers

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;
}
like image 111
Elias Van Ootegem Avatar answered Oct 18 '22 20:10

Elias Van Ootegem


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.

like image 28
unwind Avatar answered Oct 18 '22 19:10

unwind