Wednesday, December 11, 2013

GTK+ C example with GUI created using Glade

This post show how to create GUI using Glade, and link the generated glade file in c code, then compile with gcc with GTK+ 3.0, to generate a executable program.


- Start glade, create something. Specify the window in TOPLEVEL with name "myname". Save as "testGlade.glade". We will refer them in our c code.

Create GUI with Glade
- Create our c source code, "test.c".
#include <gtk/gtk.h>

int main(int argc, char *argv[])
{
    GtkBuilder *gtkBuilder;
    GtkWidget *window;
    gtk_init(&argc, &argv);
    
    gtkBuilder = gtk_builder_new();
    gtk_builder_add_from_file(gtkBuilder, "testGlade.glade", NULL);
    window = GTK_WIDGET(gtk_builder_get_object(gtkBuilder, "mywindow"));
    
    g_object_unref(G_OBJECT(gtkBuilder));
    gtk_widget_show(window);
    gtk_main();
    
    return 0;
}

where "mywindow" is the window defined in Glade. And "testGlade.glade" is our saved glade file.

- Compile it with command:
$ gcc -Wall -g -o testGlade test.c `pkg-config --cflags --libs gtk+-3.0`

Where testGlade is the target executable file. Run it:
$ ./testGlade

Because we have do nothing on the code. The program just show a menu bar without action.





Remark:

It's commented to use following command:
gcc -Wall -g -o testGlade test.c $(pkg-config --cflags gtk+-3.0) $(pkg-config --libs gtk+-3.0)

~ thx teknikkim

5 comments:

Unknown said...

I had trouble building the program on my RPi using your command. However, this worked:

gcc -Wall -g -o testGlade test.c $(pkg-config --cflags gtk+-3.0) $(pkg-config --libs gtk+-3.0)

Erik said...

thx for your comment:)

Anonymous said...

(testGlide:13088): Gtk-CRITICAL **: gtk_widget_show: assertion 'GTK_IS_WIDGET (widget)' failed
I get this error. I have done everything you did. I was wondering if your code or you methods dont work any more, because i cant find an answer.

zmh tech said...

You can fix the error by looking at what your window in glade is called. In his picture it is called mywindow and that is why it works. mine was default as applicationwindow1

Unknown said...

I was looking for a C program with a windows interface for a project with my raspberry PI. This worked out for me and I will investigate further. Thanks