Click here to Skip to main content
15,879,326 members
Articles / Desktop Programming / Win32

Starting with GTK+

Rate me:
Please Sign up or sign in to vote.
4.00/5 (8 votes)
22 Jun 2009CPOL9 min read 37.9K   342   27   2
GTK+ is a GUI widget toolkit. This article describes how I have compiled a Hello World GTK+ program to allow me to evaluate it.

Image 1

Introduction

I am not a GTK+ expert, I am an absolute beginner at using it. I have been pretty impressed with it so far. If you told me a week ago that I would be able to write a 25 line prototype program with a large selection of resizable controls all resizing correctly, I would have thought you were mad.

In this article, I will show how I:

  • Downloaded and tested the gtkmm libraries
  • Wrote an empty program that links to the gtkmm libraries
  • Downloaded, installed, and used a program called Glade which can be used to design GTK+ interfaces
  • Used Glade to design a UI
  • Created an impressively short program which prototypes a user interface
  • Added code to make the program quit from the menu not just the X

Background

I have heard a lot and read a lot about GTK+, and am interested in using it for programs I write. I have heard different things about GTK+, some people like it, some have mentioned that it flickers when you resize windows. The best ways to work out how good it is will no doubt be to compile it myself and check it out. This article documents my experience, and I hope will enable you to do the same. Using this method, I have found out that there is no flicker issue when resizing windows. (Not even on my VM, the GTK-demo works fine!)

Prerequisites for following this tutorial

I have created a Code Project article that completely shows how I set up the tool chain I use for compiling C++ programs. It is at Open Source tool.

Downloaded and tested gtkmm libraries

I am using gtkmm not GTK+. gtkmm is a C++ wrapper for GTK and GTK+ and other necessary libraries that come as part of its installation.

I downloaded the Windows installer from http://ftp.gnome.org/pub/GNOME/binaries/win32/gtkmm/2.16/ (I used gtkmm-win32-devel-2.16.0-3.exe).

I ran the installer with the following options:

  • User: anyone who uses this computer
  • Destination folder: c:\code\gtkmm
  • Type of install: Full

If you choose a different destination folder, I recommend one with no spaces in it. This makes linking etc. easier.

Next, I added the gtkmm bin directory to the path. To do this, go to Control Panel -> System -> Advanced -> Environment Variables. Under the system variables section, find the path variable and press Edit. Add the C:\code\gtkmm\bin directory to the end (addresses are seperated by ;).

Note: Don't surround the path with "'s. This will cause make to not find the directory (although the normal shells will).

Finally, you can't be sure you have done anything until you have tested. To test this, click the blue m and enter the command gtk-demo (you can do Start -> Run -> cmd and use the Windows command shell and it will still work. I just prefer MSYS.) The gtk-demo program is very interesting as it shows what you can achieve with GTK+.

Another important test is to type the following at the command line: pkg-config --cflags gtk+-2.0 (if you are using MSYS, you can copy this command and paste it into MSYS using Shift + Insert).

Note: If you want to find out more about GTK+, the website is http://www.gtk.org.

Note: If you want to find out more about gtkmm, the website is http://www.gtkmm.org/download.shtml.

Write an empty program that links to the GTK+ libraries

I frequently have difficulty compiling and linking a new library. I find it is easier to fix these problems with an empty program. To do this, I followed these steps:

Make a directory for our GTK hello world application (run these commands in MSYS):

  • cd /c/code/
  • mkdir gtk_hello_world

Create the C++ program:

  • "/c/program files/notepad++/notepad++.exe" /c/code/gtk_hello_world/main.cpp
  • Paste in the following code, then save and close Notepad++:
C++
//main.cc
#include <gtkmm/main.h>
#include <gtkmm/menu.h>
#include <libglademm.h>
#include <gtkmm/window.h>
#include <gtkmm/button.h>

int main( int argc, char *argv[] )
{
    printf("gtk_hello_world start\n");
    printf("gtk_hello_world end\n");
    return 0;
}

Don't forget the newline at the end of the file, and make sure the <'s and >'s get copied OK.

Create the Makefile

  • "/c/program files/notepad++/notepad++.exe" /c/code/gtk_hello_world/makefile
  • Paste in the following code, then save and close Notepad++:
$(warning Starting Makefile)

CXX=g++

main.exe: main.cpp
    $(CXX) main.cpp -o main.exe `pkg-config gtkmm-2.4 libglademm-2.4 --cflags --libs`

clean: 
    -rm main.exe

While you have either the main.cpp or makefile open in Notepad++, click Run -> RUN_CODE. This will compile and run the program, and you should see gtk_hello_world start and gtk_hello_world end appear on the screen.

Download, install, and use a program called Glade which can be used to design GTK+ interfaces

When I first looked at GTK+ and reached this point, I ploughed into writing code to create windows and widgets (in GTK+, buttons, controls etc., are called widgets). After a couple of days of learning about this, I found an article describing Glade and using it to design GTK+ user interfaces. This is a much better way of developing applications, and I really wish I had found this article first. It is still handy to know how to create widgets using code as this helps with dynamic creation while your program is running. When you develop applications, most of the window design is static, and you can use Glade to do the design work without writing endless code.

Glade is a UI designer program, not a full IDE. You use it to create the user interface and save it as an XML file. You then write a program which uses libglade to load the XML file and creates all the controls etc.

When I tried this, the Glade site had a broken link to the download (http://glade.gnome.org/download.html). I eventually found a correct link and downloaded glade-3.4.3-win32-1.zip from http://sourceforge.net/project/showfiles.php?group_id=98754&package_id=105780.

Windows can unzip, but I used a program called 7-zip to do this. I placed the files in the directory C:\Program Files\glade\.

Create a shortcut to C:\Program Files\glade\bin\glade-3.exe on the desktop or somewhere where it is easily available.

Note: If you want to find out more about Glade, the website is http://glade.gnome.org/.

Use Glade to design a UI

Now, you can run Glade using the shortcut. Designing the UI is not a simple matter of dragging and dropping buttons and textboxes as GTK uses a concept called packing, so I will go through some actions which create a UI. I have added the XML file for this to the article, but I recommend going through these steps and creating it for yourself.

  • Under Top-levels, click the first icon (Window) - This will make a window appear.
  • Under Containers, click the second icon (Vertical Box) and then click inside the window. Under number of items, enter 4.
  • Under Containers, click the seventh icon (Menu Bar) and then click on the top area that just appeared.
  • Under Containers, the eighth icon is Tool Bar. Click it once, then click in the second area.
  • The twenty fifth icon under Control and Display is the status bar. Put it in the bottom section of the window.
  • The forth icon under Containers is Notebook. Put this in the remaining section, with one page. (It will add three pages, but you can right click and remove two of them).
  • Finally, add a text view (Control and Display, fourteenth icon).

Now, we have the controls set up, and we need to name some of them to access them. Normally, you would name them all; I'm just going to go through the ones I need in my example.

  • Select the main window (probably called window1) and set its name to main_window.
  • Still under window1, set the default width to 400 and the default height to 250.
  • We need to name the quit menu option. You can access the file menu by clicking on it and then the popup will appear. Click on Quit to select it, and set its name to menu_file_quit.

Now that you have finished, you can save the XML file. Save it as c:\code\gtk_hello_world\ui.glade. Now quit Glade.

Note: I have put ui.glade in the zip file for this article. You can skip this stage and just copy it to c:\code\gtk_hello_world\ui.glade if you want to.

Create an impressively short program which prototypes a user interface

Glade used to create source code for you to compile, but it doesn't do this any more. The current method is to export an XML file (ui.glade, in our case), and you use libglade to create the UI.

Make changes to the C++ file so it looks like this:

  • "/c/program files/notepad++/notepad++.exe" /c/code/gtk_hello_world/main.cpp
  • Paste in the following code, then save and close Notepad++:
C++
//main.cc
#include <gtkmm/main.h>
#include <gtkmm/menu.h>
#include <libglademm.h>
#include <gtkmm/window.h>
#include <gtkmm/button.h>

int main( int argc, char *argv[] )
{
    printf("gtk_hello_world start\n");
    
    Gtk::Window* pMainWindow = 0;
    Gtk::Main kit( argc, argv );
    Glib::RefPtr refXml = Gnome::Glade::Xml::create("ui.glade");
    refXml->get_widget("main_window", pMainWindow);
    if (0==pMainWindow) {
        printf("Couldn't find main window in ui.glade\nExiting\n");
        return 0;
    };
     Gtk::Main::run (*pMainWindow);
    
    printf("gtk_hello_world end\n");
    return 0;
}

Don't forget the newline at the end of the file, and make sure the <'s and >'s get copied OK.

Wow, we now have a 25ish lines of code which has all the components of a multi-tab text editor. It also resizes perfectly, and we can redesign the UI without recompiling! GTK+ uses packing containers which is what we were doing when designing the UI; this has eliminated the need for any code to be written to deal with resizing.

Add a code to make the program quit from the menu not just the x

I will show a simple extension to show how to code the quit menu item so it quits.

Add the following function to the C++ file after the includes but before the main function:

C++
void on_quit_clicked()
{
    gtk_main_quit ();
}

Then, change the main function of the C++ program so it matches the following:

C++
printf("gtk_hello_world start\n");

Gtk::Main kit( argc, argv );
Glib::RefPtr refXml = Gnome::Glade::Xml::create("ui.glade");

Gtk::Window* pMainWindow = 0;
refXml->get_widget("main_window", pMainWindow);
if (0==pMainWindow) {
    printf("Couldn't find main window in ui.glade\nExiting\n");
    return 0;
};

Gtk::ImageMenuItem* pMenuQuit = 0;
refXml->get_widget("menu_file_quit", pMenuQuit);
if (0==pMainWindow) {
    printf("Couldn't find menu_item_quit in ui.glade\nExiting\n");
    return 0;
};
pMenuQuit->signal_activate().connect(sigc::ptr_fun(&on_quit_clicked));

Gtk::Main::run (*pMainWindow);

printf("gtk_hello_world end\n");
return 0;

I have also included this version of main.cpp in the zip file for this article.

Note that the code finds pointers to objects we defined in Glade. Also note the connect function which connects a signal to a procedure we have written.

If you make and run this (Run->RUN_CODE), you will see the program run with the quit menu working.

Points of interest

Using Glide and GTK+ together seems like a really fast method of developing applications. Using the code I have included in this article, you can get UIs you create to run almost smoothly. Connecting the UI objects to functions seems pretty easy. This seems very powerful to me, and I will be delving deeper and creating applications using this.

Feedback

The point of this article was to save time for people who wanted to check out GTK+. I hope I have achieved this aim; if you have followed these steps and encountered problems, feedback would be appreciated as I may be able to improve the article.

There are alternatives to GTK+. QI springs to mind. At some point, I am hoping to write an article about this.

History

  • 13-Jun-2009 - First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalerror: Missing template definition Pin
HomeSen6-Jul-09 23:39
HomeSen6-Jul-09 23:39 
GeneralRe: error: Missing template definition Pin
QoSyS30-Aug-09 9:37
QoSyS30-Aug-09 9:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.