The MagPi - February 2020

(Greg DeLong) #1
(You can select one of two different formats on the
save window – use the default GtkBuilder option.)
Make sure you save the file in the same directory
where you are storing your GTK source code.

Using a layout file in a GTK application
Now we need to load the layout file into some GTK
code. Try the following:

#include <gtk/gtk.h>

void main (int argc, char *argv[])
{
gtk_init (&argc, &argv);

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

GtkWidget *win = (
GtkWidget *) gtk_builder_get_object (
builder, "window1");
gtk_widget_show_all (win);
gtk_main ();
}

The gtk_init and gtk_main calls are the same as
we have seen before, but the code between them
uses a GtkBuilder, a code object which reads in and
processes a layout file.
We create a GtkBuilder object:

GtkBuilder *builder = gtk_builder_new ();

We then read the layout file into the builder.

gtk_builder_add_from_file (builder,
"mylayout.glade", NULL);

The widgets we created in the layout file can now
all be accessed by calls to gtk_builder_get_object,
and used as before. So we get the object which was
named window1 in the layout file.

GtkWidget *win = (
GtkWidget *) gtk_builder_get_object (
builder, "window1");

And we show it as before:

gtk_widget_show_all (win);

If you build and run this code, our simple window
should be displayed on the screen (Figure 6).
To make the widgets actually do things, we need
to connect signals as before, so let’s modify our
code accordingly.

Figure 3 Adding
a vertical box

To make the widgets


actually do things, we need


to connect signals


Figure 3


TUTORIAL


56 magpi.cc Glade layout editor with C and GTK

Free download pdf