C语言 用GTK按钮创建网格



我想创建一个带有按钮的网格。当单击按钮时,我希望它改变颜色,并根据按钮的当前状态将0或1存储在数组中。

现在我通过创建带有两个for循环(行和列)的按钮来实现这一点。for循环内;

/*Create an ID number for the button being created*/
btn_nr ++;
char btn_nr_str[3];
sprintf(btn_nr_str,"%d",btn_nr); //convert nr to string
/*Create button*/
button = gtk_button_new();
/* When the button is clicked, we call the "callback" function
 * with a pointer to the ID */
gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (callback)(gpointer) btn_nr_str);
/* Insert button into the table */
gtk_table_attach_defaults (GTK_TABLE(table), button, col, col+1, row, row+1);
gtk_widget_show (button);

回调函数;

void callback( GtkWidget *widget, gpointer nr)
{
    GdkColor buttonColor;
    gdk_color_parse ("black", &buttonColor);
    gtk_widget_modify_bg ( GTK_WIDGET(widget), GTK_STATE_NORMAL, &buttonColor);
    g_print ("Hello again - %s was pressedn", (char *) nr);
}

按钮创建像想要的,当点击他们变成黑色。但是,所有按钮都打印最后创建的按钮的ID。

如何传递正确的ID ?

您正在从外部(回调)其作用域(for循环)访问本地数组(btn_nr_str)。这个想法是正确的(使用user_data),但实现不是。

对于您的具体情况,您可以使用GLib提供的类型转换宏。它们的目的就是:

/* In the for cycle */
g_signal_connect(button, "clicked", G_CALLBACK(callback), GINT_TO_POINTER(btn_nr);
/* In the callback */
gint btn_nr = GPOINTER_TO_INT(user_data);

注:: gtk_signal_connect早在几年前就被弃用了

最新更新