Search code examples
cgtk

How to use inherited method of a GTK 4.0 class in C


I'm writing a program in C (not C++) using Gtk4.

I want to handle mouse clicks (and maybe other events) in a single handler.

/* Setting up the handler */
static void activate(GtkApplication *app, gpointer data) 
{
  /* ... */
  click = gtk_gesture_click_new();
  /* ... */
  g_signal_connect(click, 
                   "pressed",
                   G_CALLBACK(click_handler),
                   drawing_area);
}

static void click_handler(GtkGestureClick   *gesture,
                          int                n_press,
                          double             x,
                          double             y,
                          GtkWidget         *area)
{
  guint button = gtk_gesture_single_get_button(gesture); /* !!! */
  switch (button) {
  case 1:
    /* handle leftclick */
    break;
  /* ... */
  }
  /* ... */
}

According to the signal's documentation GtkGestureClick will be passed to the handler, but gtk_gesture_single_get_button() needs it's parent class GtkGestureSingle

My question is, how to use inherited methods of a Gtk class instance in C?

I was thinking just simply casting it to it's parent's type, but I'm not sure if this is "The Gtk way".

Also if you could attach the page where this info could be looked upon, that would be nice. I was looking around on Gtk4's and GObject's documentation, but I didn't find what I need.


Solution

  • I was thinking just simply casting it to it's parent's type, but I'm not sure if this is "The Gtk way".

    You are close but not fully correct. If you only use a cast, you might satisfy your compiler's demands but AFAIK there is type information stored in GTK objects which will not match.

    You can see what the Gtk way is here:

    If you have a derived object (GtkWidget*window) but need a parent class (GtkWindow*) you can convert it with GTK_WINDOWS(window).

    In your snippet above the same mechanism is used G_CALLBACK(click_handler). These macros do what's needed which is a bit more than a simple cast.

    For your code, try to use GTK_GESTURE_SINGLE(gesture).