来自按钮数组的 GTK 信号 C 语言

GTK signals from array of buttons C language

我已经在 C 语言的 GTK 中创建了一个按钮数组,但我遇到了一个问题 - 我如何从它们捕获信号?

 GtkWidget *board[10][10];
 for( i=0; i < 10; i++) {
        for( j=0; j < 10; j++) {
          board[i][j] = gtk_button_new();
        }
  }

我当然可以这样一个一个做

  g_signal_connect (board[0][0], "clicked", G_CALLBACK(show_info), NULL;

但我打算做一个棋盘游戏,会有 100 个按钮...有没有办法,可以在一个功能中完成?例如,我想改变被点击按钮的颜色,但我不知道如何为此编写代码。

非常感谢您的帮助。

一种方法是动态分配一些要传递给回调的用户数据。

typedef struct {
    int x;
    int y;
} coordinate;

int main(int argc, char *argv[]) {
    // ... some code here
    for(i=0; i<10; i++) {
        for(j=0; j<10; j++) {
            coordinate *c = malloc(sizeof *c);
            c->x = i;
            c->y = j;
            board[i][j] = gtk_button_new();
            g_signal_connect_data(board[i][j],
                                  "clicked",
                                  G_CALLBACK(show_info),
                                  c,
                                  (GClosureNotify)free,
                                  0);
        }
    }
    // some other code
}

然后在回调中:

void show_info(GtkButton *button, gpointer userdata) {
    coordinate *c = userdata;
    // use c->x and c->y to determine which button is pressed
}