在GTK3 +

时间:2017-12-04 11:35:52

标签: c dialog gtk3

单击gtk_drawing_area时,我正在尝试显示信息对话框窗口。

以下是我正在使用的代码:

#include <cairo.h>
#include <gtk/gtk.h>

void show_dialog_window(GtkWidget *widget, gpointer window) {

  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_DESTROY_WITH_PARENT,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "Hello dialog!");
  gtk_window_set_title(GTK_WINDOW(dialog), "Information");
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(dialog);
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *darea;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 400, 300); 
  gtk_window_set_title(GTK_WINDOW(window), "Click me to show an Info_Dialog");

  darea = gtk_drawing_area_new();
  gtk_container_add(GTK_CONTAINER(window), darea);

  gtk_widget_add_events(window, GDK_BUTTON_PRESS_MASK);

  g_signal_connect(window, "destroy",
      G_CALLBACK(gtk_main_quit), NULL);  
  g_signal_connect(window, "button-press-event", 
      G_CALLBACK(show_dialog_window), (gpointer) window); 


  gtk_widget_show_all(window);

  gtk_main();

  return 0;
}

当我使用 gcc dialog.c pkg-config --cflags gtk+-3.0 --libs --libs cairo命令编译并运行此代码时,-lm -o dialog&amp;&amp; ./dialog 我在终端上收到以下信息:

分段错误(核心转储)

关于我做错了什么的任何建议?

1 个答案:

答案 0 :(得分:2)

问题在于回调函数。您正在使用以下原型:

void user_function(GtkWidget *widget, gpointer window)

它应该是,如API reference

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

调整你的回调,它应该是这样的:

gboolean show_dialog_window(GtkWidget *widget, GdkEvent *event, gpointer window) {

  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_DESTROY_WITH_PARENT,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "Hello dialog!");
  gtk_window_set_title(GTK_WINDOW(dialog), "Information");
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(dialog);
  return TRUE;
}

返回TRUE将停止信号传播。

更改后,程序应该可以正常工作。您可以访问event中的事件信息,例如按下了哪个按钮等