PintoDoido
PintoDoido

Reputation: 1051

Error displaying Info Dialog in GTK3+

I am trying to display a info dialog window when the gtk_drawing_area is clicked.

Here is the code I am using:

#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;
}

When I compile and run this code using the command gcc dialog.c pkg-config --cflags gtk+-3.0 --libs --libs cairo -lm -o dialog && ./dialog I get the following on the terminal:

Segmentation fault (core dumped)

Any suggestion as to what I am doing wrong?

Upvotes: 1

Views: 124

Answers (1)

Jos&#233; Fonte
Jos&#233; Fonte

Reputation: 4114

The problem resides on the callback function. You are using the following prototype:

void user_function(GtkWidget *widget, gpointer window)

and it should be, as documented in the API reference:

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

Adapting your callback, it should be something like this:

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;
}

Returning TRUE will cease signal propagation.

After the change, the program should work fine. You can access event information in event, such as which button was pressed, etc.

Upvotes: 2

Related Questions