问题
I tried to make a simple Gui program with C and Glade on Linux. I wrote a simple program and design a window with Glade. When I run the code it says:
(gtk-test:23026): Gtk-CRITICAL **: gtk_widget_show: assertion ‘GTK_IS_WIDGET(widget)’ failed
And no Window open. I searched a bit on the internet but I cant anything helpful. Some say that I have to convert the glade file to .xml but that didn't work.
C
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
GtkBuilder *builder;
GtkWidget *window;
gtk_init(&argc, &argv);
builder = gtk_builder_new();
gtk_builder_add_from_file (builder, "window_main.glade", NULL);
window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
gtk_builder_connect_signals(builder, NULL);
g_object_unref(builder);
gtk_widget_show(window);
gtk_main();
return 0;
}
void on_window_main_destroy()
{
gtk_main_quit();
}
Glade
<?xml version=1.0 encoding="UFT-8"?>
<!-- Generated with glade 3.18.3 -->
<interface>
<requires lib="gtk+" version="3.12"/>
<object class="GtkWindow" id="window_main">
<property name="can_focus">False</property>
<property name="title" translatable="yes">Test Window</property>
<property name="default_width">640</property>
<property name="default_height">480</property>
<signal name="destroy" handler="on_window_main_destroy" swapped="no"/>
<child>
<placeholder/>
</child>
</object>
</interface>
回答1:
It seems you add the xml tag by hand and it's malformed. At the same time you are not doing any error checking from the gtk_builder_add_from_file
function.
Your xml starts with:
<?xml version=1.0 encoding=UFT-8>
and should be:
<?xml version="1.0" encoding="UTF-8"?>
To avoid this situation you should use GError and check if there are errors when parsing the builder file with gtk_builder_add_from_file
.
EDIT:
I saw that you have updated the glade file in your question. If you do so then the answer may not be obvious. Anyway, here is your code with error checking for glade file existence and @underscore_d
tip on checking the GtkBuilder get_object
function (could use g_assert
macro instead):
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
GError *err = NULL;
GtkBuilder *builder;
GtkWidget *window;
gtk_init(&argc, &argv);
builder = gtk_builder_new();
gtk_builder_add_from_file (builder, "window_main.glade", &err);
if (err != NULL) {
fprintf (stderr, "Unable to read file: %s\n", err->message);
g_error_free(err);
return 1;
}
window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
if (window == NULL || !GTK_IS_WINDOW(window)) {
fprintf (stderr, "Unable to get window. (window == NULL || window != GtkWindow)\n");
return 1;
}
gtk_builder_connect_signals(builder, NULL);
g_object_unref(builder);
gtk_widget_show(window);
gtk_main();
return 0;
}
void on_window_main_destroy(GtkWidget *widget, gpointer user_data)
{
gtk_main_quit();
}
Compile with:
gcc -rdynamic -o window main.c `pkg-config --cflags --libs gtk+-3.0`
来源:https://stackoverflow.com/questions/45752987/gtk3-c-glade-problems