GTK + Use one handler for multiple widgets

I have a callback function:

void handle(GtkWidget *widget, gpointer data) {...}

Since I have many widgets for this window, I would like to use this callback as the only handler to avoid writing many small functions. I initially thought about using an enumeration stored in a user interface class that wraps around a window, and then I will test it as follows:

UIClass::Signal signal = (UIClass::Signal) data;
switch (signal) {
  case UIClass::main_button:
    // handle
  case UIClass::check_box:
  ...
}

But the compiler refuses translation in the first line of this fragment.

Is there a standard way to do this? Or was GTK + designed to have one handler for each widget?

+4
source share
1 answer

:

#include <gtk/gtk.h>
#include <iostream>

struct UIClass
{
    GtkWidget* widget1, *widget2, *box;
    UIClass()
    {
        widget1 = gtk_button_new_with_label("button1");
        widget2 = gtk_button_new_with_label("button2");

        box = gtk_hbox_new(true, 10);
        gtk_box_pack_start(GTK_BOX(box), widget1, 0 ,0, 1);
        gtk_box_pack_start(GTK_BOX(box), widget2, 0 ,0, 1);
    }

    static void handle(GtkWidget* sender, UIClass* uiClass)
    {
        if(sender == uiClass->widget1)
            std::cout<<"widget1"<<std::endl;
        else if(sender == uiClass->widget2)
            std::cout<<"widget2"<<std::endl;
        else
            std::cout<<"something else"<<std::endl;
    }

    void connect()
    {
        g_signal_connect(widget1, "clicked", G_CALLBACK(UIClass::handle), this);
        g_signal_connect(widget2, "clicked", G_CALLBACK(UIClass::handle), this);
    }
};

int main(int argc, char *argv[])
{
  gtk_init (&argc, &argv);

  GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  UIClass ui;
  ui.connect();

  gtk_container_add(GTK_CONTAINER(window), ui.box);

  gtk_widget_show_all(window);
  gtk_main();

  return 0;
}
0

Source: https://habr.com/ru/post/1680368/


All Articles