在C中使用“GtkWidget * window”与“GObject * window”

时间:2016-05-04 20:23:43

标签: c gtk gtk3 gobject

使用GTK + 3(和glade)从xml glade文件创建简单窗口时,正确的语法是什么?我已经看到两种似乎做同样事情的方法,但语法略有不同。

示例1:

#include <gtk/gtk.h>

int
main (int argc, char *argv[])
{
  GtkBuilder *builder;
  GObject *window;

  gtk_init (&argc, &argv);

  builder = gtk_builder_new ();
  gtk_builder_add_from_file (builder, "builder.glade", NULL);

  window = gtk_builder_get_object (builder, "window");
  g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);

  gtk_main ();

  return 0;
}

示例2:

#include <gtk/gtk.h>

void 
on_window_destroy (GtkWidget *object, gpointer user_data)
{
    gtk_main_quit ();
}

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

    gtk_init (&argc, &argv);

    builder = gtk_builder_new ();
    gtk_builder_add_from_file (builder, "builder.glade", NULL);

    window = GTK_WIDGET (gtk_builder_get_object (builder, "window"));
    gtk_builder_connect_signals (builder, NULL);

    g_object_unref (G_OBJECT (builder));

    gtk_widget_show (window);                
    gtk_main ();

    return 0;
}

1 个答案:

答案 0 :(得分:4)

两者都应该有效,但我认为使用GtkWidget更合理,因为你需要更多这种类型,所以你不需要一直写GTK_WIDGET(obj)。你只需要“转换”一次。

请注意,官方指南使用GObject类型。 (here

但毕竟你可以决定,因为你可以很容易地“转换”它到你需要的类型......