如何在C中正确地将结构体传递给GTK4中的g_signal_connect?

问题描述 投票:0回答:1

我试图将结构体的地址传递给 g_signal_connect 的 gpointer 数据参数,以便回调函数可以在单击按钮时打印结构体的 int 成员。我是 GTK 的新手,很困惑为什么它不起作用。

我期望回调函数(print_location)中的打印函数能够正确打印 1 和 5,但它们却打印 0 和 0。我使用了 GTK 将结构传递给 C 中的回调函数中的最佳答案作为参考,但它没有似乎不在这里工作。

#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
struct data{
        int row;
    int column;
};

void print_location(GtkWidget *widget, gpointer user_data)
{
    struct data *d = user_data;
    printf("clicked\n");
        // these do not print as expected
    printf("row: %d\n", d->row);
    printf("col: %d\n", d->column);
}

static void activate (GtkApplication *app, gpointer user_data)
{
  GtkWidget *window;
  GtkWidget *grid;
  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  grid = gtk_grid_new ();
  gtk_window_set_child (GTK_WINDOW (window), grid);


  // example row and column data
  struct data d;
  d.row = 1;
  d.column = 5;
  // sanity check
  struct data *c = &d;
  printf("row: %d, col: %d\n", c->row, c->column); // this prints as expected
  // end of sanity check
  GtkWidget *button;
  button = gtk_button_new();
  gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);
  
  // passing the struct here
  g_signal_connect(button, "clicked", G_CALLBACK(print_location), &d);

  gtk_window_present (GTK_WINDOW (window));
}

int main (int argc, char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.test", G_APPLICATION_DEFAULT_FLAGS);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

我还是 GTK 的新手,总体来说对 C 不太有经验,所以这里的任何帮助将不胜感激。谢谢。

c callback gtk signals gtk4
1个回答
0
投票

这个问题已经在这里得到解答了。

无法通过单击 C 中的 gtk4 按钮向框添加标签

typedef struct {
  GtkWidget* prompt;
  GtkWidget* box;
} MyWidgets;


// Create a data structure to hold multiple pieces of data
    static MyWidgets widgets;
    MyWidgets *widgets_ptr =&widgets ;
    widgets_ptr->box = box;
    widgets_ptr->prompt = prompt;

// When the button is clicked, passed as an argument
g_signal_connect((GtkButton*)button, "clicked", G_CALLBACK(on_button_clicked),widgets_ptr);

希望我能帮上忙。如果没有,请提供一些代码。

© www.soinside.com 2019 - 2024. All rights reserved.