GTK - 如何将参数传递给GtkEventBox

时间:2017-03-08 12:39:15

标签: c linux gtk gnome

此代码创建一个带有标签的窗口的程序,如果单击该标签,程序将执行作为g_signal_connect(G_OBJECT(eventbox), "button_press_event", G_CALLBACK(on_event_clicked), buffer)参数传递的缓冲区的fprintf。以前程序放入缓冲区字符串“Hello Word”然后程序应该打印此消息,但程序可能只打印乱码字符。哪里我错了?

#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);
}

1 个答案:

答案 0 :(得分:2)

on_event_clicked()的原型是错误的,它与GTK +期望的不匹配。

应该是:

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

您需要将缺少的参数添加到函数中,并且还要处理返回值的要求。请认真对待read the signal documentation