无法将参数传递给GTK回调

时间:2013-02-11 07:05:05

标签: c++ pointers gtk

当程序最初运行时,打印语句,打印对应于指针的有效十六进制代码。但是,当我单击屏幕,并通过“clicked”回调调用handleClick方法时,会在屏幕上显示0x0。发生了什么?为什么我的电路板对象突然变为空?

#include <stdio.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include "board.h"

void printBoard(Board *board);
void handleClick(GtkWidget *widget, GdkEventButton *event, cairo_t *cr, gpointer data);

  gboolean draw_cb(GtkWidget *widget, cairo_t *cr, gpointer data)
  {
    Board *temp = (Board *)data;
    printf("%p\n",temp);
    return TRUE;
  }

  void handleClick (GtkWidget *widget, GdkEventButton *event, cairo_t *cr, gpointer data)
  {
    Board *temp = (Board *)data;
    printf("%p\n",temp);
  }

  void start(Board *newBoard)
  {
      GtkWidget *window;
      GtkWidget *da;
      GtkWidget *frame;

      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
      char string[40];
      snprintf(string, sizeof(string), "Connect %d-%d",newBoard->k,newBoard->n);

      gtk_window_set_default_size (GTK_WINDOW(window), 400, 400);
      gtk_window_move(GTK_WINDOW(window), 100, 100);     
      g_signal_connect (GTK_WINDOW(window), "destroy", G_CALLBACK (gtk_main_quit), NULL);

      da = gtk_drawing_area_new ();
      gtk_widget_set_size_request (da, 500, 500);

      frame = gtk_frame_new (NULL);
      gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
      gtk_container_add (GTK_CONTAINER (window), frame);

      gtk_container_add (GTK_CONTAINER (frame), da);

      gtk_widget_set_events (da, gtk_widget_get_events (da)
                     | GDK_BUTTON_PRESS_MASK);

      g_signal_connect (da, "draw",
              G_CALLBACK (draw_cb), newBoard);

       g_signal_connect (da, "button-press-event",
              G_CALLBACK (handleClick), newBoard);

      gtk_widget_show_all (window);
  }

2 个答案:

答案 0 :(得分:1)

根据reference manualbutton-press-event信号处理程序的原型如下。

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

如果您从cairo_t *cr功能handleClick删除data参数即可。

答案 1 :(得分:0)

正如Szilard所说,你正在使用handleClick函数的错误原型。

button-press-event信号处理程序具有以下原型:

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

要解决您的错误,您需要:

  • 删除cairo_t *cr参数。它收到data的值。
  • 修复event类型GdkEvent *,而不是GdkEventButton *
  • 修复返回值,这是一个布尔值,而不是无效,这对于确定事件是否传播很重要。