gpt4 book ai didi

使用 GTK 按钮创建网格

转载 作者:太空宇宙 更新时间:2023-11-04 08:57:26 25 4
gpt4 key购买 nike

我想创建一个带有按钮的网格。单击按钮时,我希望它改变颜色,并根据按钮的当前状态将 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 pressed\n", (char *) nr);
}

按钮是按需要创建的,单击时它们会变黑。但是,所有按钮都会打印最后创建的按钮的 ID。

如何传递正确的 ID?

最佳答案

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

对于您的具体情况,您可以使用 type conversion macrosGLib 提供。它们正是为了这个目的而设计的:

/* 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 多年前就已弃用。

关于使用 GTK 按钮创建网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com