Search code examples
clinuxgtkgnome

GTK - How to pass an argument to a GtkEventBox


This code make a program that create a window with label, if you click the label, the program executes an fprintf of buffer passed as an argument of g_signal_connect(G_OBJECT(eventbox), "button_press_event", G_CALLBACK(on_event_clicked), buffer). Previously the program put in buffer the string "Hello Word" and then the program should print this message, but maybe the program print only garbled char. Where I'm wrong?

#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>
void on_event_clicked (GtkWidget* widget, gpointer user_data);

int main (int argc, char **argv) {
    GtkWidget   *window;
    GtkWidget   *eventbox;
    GtkWidget   *label;
    char*       buffer = malloc(sizeof(char)*10);

    strcpy(buffer, "Hello Word\0");

    gtk_init (&argc,&argv);

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    label = gtk_label_new ("Hello Word");
    eventbox = gtk_event_box_new ();

    gtk_container_add (GTK_CONTAINER(eventbox), label);
    gtk_container_add (GTK_CONTAINER(window), eventbox);
    gtk_widget_show_all (window);

    g_signal_connect(G_OBJECT(window), "destroy",
                     G_CALLBACK(gtk_main_quit), NULL);

    g_signal_connect(G_OBJECT(eventbox), "button_press_event",
                     G_CALLBACK(on_event_clicked), buffer);

    gtk_main();

    return 0;
}

void on_event_clicked (GtkWidget *widget, gpointer user_data) {
    char* pn = user_data;
    fprintf(stderr, "%s\n", pn);
}

Solution

  • Your prototype for on_event_clicked() is wrong, it doesn't match what GTK+ expects.

    It should be:

    gboolean user_function (GtkWidget *widget, GdkEvent *event, gpointer user_data);
    

    You need to add the missing argument to your function, and also deal with the requirement for a return value. Remember to read the signal documentation seriously.