Jump to content

GTK+ By Example/Print version

From Wikibooks, open books for an open world

Permission is granted to copy, distribute and/or modify this document under the terms of the Creative Commons Attribution/Share-Alike License.

Contents

If you have saved this file to your computer, click on a link in the contents to go to that section.

Introduction

About This Book

GTK+ is a cross-platform Graphical User Interface (GUI) programming library. It is most well known for it's association with the GNOME desktop environment.

GTK+ is supported in:

  • UNIX/Linux
  • OS X
  • Microsoft Windows

Prerequisite Knowledge

We assume a working knowledge of the C programming language. You should be familiar with functions, pointers and file operations. If you need a refresher, you should consider the excellent book by Kernighan and Ritchie, ISBN: 0131103628.

In addition, you will require basic skills with the command line, a compiler, Make and an editor of your choice.

Aims

  • Accessible introduction to the GTK+ windowing toolkit
  • Get started building programs from the beginning

Beginning

In this chapter, we will look at some very simple GTK+ examples, starting off with the classic "Hello, world!".

  1. You will find you learn more effectively by getting stuck in and writing code.
  2. Make sure you understand what you are doing before you move on to the next chapter. Chapters in this book are designed to be completed as individual units but background knowledge of previous chapters is assumed.
  3. You can copy and paste code to get quick results but typing out by hand will help you familiarise yourself with GTK+ coding style and is therefore recommended.
  4. Take it slow and tell yourself how wonderful you are for getting each example working.
  5. Make mistakes changing the code: get things wrong and have fun!

Compiling the examples

When you compile these example programs, you may need to pass additional information to the command line to enable the GTK+ windowing libraries.

On Linux, you will need to ensure that you have the program pkg-config.

gcc -Wall -g helloworld.c -o helloworld `pkg-config --cflags gtk+-2.0` `pkg-config --libs gtk+-2.0`

More information is available here: https://developer.gnome.org/gtk-tutorial/stable/x111.html

An empty window

In this example we create a single window, set its title and size and connect an event that allows the application to close.

#include <gtk/gtk.h>

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

  /* Initialise GTK+ passing to it all command line arguments  */
  gtk_init (&argc, &argv);

  /* create a new window, set values */
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Hello GTK+ World");
  /* set the size of the window */
  gtk_widget_set_size_request (GTK_WIDGET (window), 200, 200);
  /* connect the windows "destroy" event */
  g_signal_connect (G_OBJECT (window), "destroy",
                    G_CALLBACK (gtk_main_quit), NULL);  

  /* set the window as visible */
  gtk_widget_show (window);

  /* run the GTK+ main loop */
  gtk_main ();
  return 0;
}


Congratulations, you have created your first GTK+ window. You may not completely understand the code you have written yet. That's alright; by the end of this chapter creating windows will be easy. GTK+ is object oriented. As C is not designed as an object oriented language you must explicitly cast objects- this will occur most often with the paramater passed to a function. You first cast window from a GtkWidget to a GtkWindow when you wrote GTK_WINDOW (window). If you don't understand this example feel free to move on after you complete two small challenges. You can probably guess how to do them easily, but don't let yourself be tricked. The act of doing even small tasks will help you focus yourself on solving large problems.

challenge: Change the name of the window to your first name.
challenge: Change the window size to 400 * 400 pixels, currently it is 200 * 200 pixels.


We will have explained everything in this example by the end of the chapter, but for now let us focus on two lines of code.

gtk_init (&argc, &argv);
gtk_init () is called at the start of all GTK+ applications, it initialises gtk+ library. &argc and &argv are passed to gtk_init (), these are command line arguments that have been passed to the application gtk_init () takes these becase it has a set of command line arguments it can accept.
gtk_main ();
gtk_main () is called once your application has been set up, once this has been called you will have to wait until gtk_main_quit () is called before the application continues. We have already connected to that event and will explain it after further excercises.

Window with a button

This example is slightly different to the last example, we have added a button also notice we have not called gtk_widget_set_size_request ().

#include <gtk/gtk.h>

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

  /* Initialise GTK+ passing to it all command line arguments  */
  gtk_init (&argc, &argv);

  /* create a new window, set values */
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Hello Button");
  /* connect the windows "destroy" event */
  g_signal_connect (G_OBJECT (window), "destroy",
                    G_CALLBACK (gtk_main_quit), NULL);  

  button = gtk_button_new_with_label ("Hello Window");
  gtk_container_add (GTK_CONTAINER (window), button);
  g_signal_connect (G_OBJECT (button), "clicked",
                    G_CALLBACK (gtk_main_quit), NULL);

  /* set the window as visible */
  gtk_widget_show_all (window);

  /* run the GTK+ main loop */
  gtk_main ();
  return 0;
}


Good work, another one bites the dust, don't move on just yet, same format as before my friend. When you click the button it closes the window, what kind of annoying application is this? One that is trying to get you to pay attention to how it is done that's what. Notice this time we did not call gtk_widget_set_size_request (), that is because GTK+ automatically sizes windows and widgets for you, for the most part you should not have to set the size of widgets or windows your self; the last example was different because we had nothing inside the window. As the name size_request suggest the size you ask for may not be the size allocated to the widget, this will be explained more further on in the book, for now understanding that it is a request should be enough.

challenge: make the button do nothing when you click it, that's right nothing.
challenge: remove the line starting with 'button =', and run your program from the command line and see what happens.


Once again we will not be explaining everything just yet, that would take the fun out of this for you. Anyhow, how did you go with the challenges? I bet you did well. Let's go through a two more lines of code:

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_new () creates a new window of one of two types, GTK_WINDOW_TOPLEVEL and GTK_WINDOW_POPUP. Don't let the name GTK_WINDOW_POPUP confuse you it is not for popup dialogs, popup dialogs and GTK_WINDOW_POPUP both will be explained in future chapters.
button = gtk_button_new_with_label ("Hello Window");
button_new_with_label () is a convenience function, in this case it means it creates a button and a label and inserts the label in the button for you. A button in GTK+ is a container that when clicked may cause a piece of code to be run. The button may hold anything you insert into it, but putting somethin in a button just for fun will really confuse people, so we suggest you insert labels or images, and if you are a great person you will learn to insert images and labels at the rate you are going you will rule the world soon.

Tree View Widget

This chapter has been based on this work [1]

Chapter Sections

  1. Lists and Trees: the GtkTreeView Widget
  2. Components: Model, Renderer, Column, View
  3. GtkTreeModels for Data Storage: GtkListStore and GtkTreeStore
  4. Creating a Tree View
  5. Mapping Data to the Screen: GtkTreeViewColumn and GtkCellRenderer
  6. Selections, Double-Clicks and Context Menus
  7. Sorting
  8. Editable Cells
  9. Miscellaneous
  10. Drag'n'Drop (DnD) **** needs revision ***
  11. Writing Custom Models
  12. Writing Custom Cell Renderers
  13. Other Resources

Original License (Tree View)

Copyright (c) 2003-2004 Tim-Philipp Müller <tim at centricular dot net>

This tutorial may be redistributed and modified freely in any form, as long as all authors are given due credit for their work and all non-trivial changes by third parties are clearly marked as such either within the document (e.g. in a revision history), or at an external and publicly accessible place that is referred to in the document (such as a CVS/SVN/git repository).

Original Version Credits

Thanks to Axel C. for proof-reading the first drafts, for many suggestions, and for introducing me to the tree view widget in the first place (back then when I was still convinced that porting to Gtk+-2.x was unnecessary, Gtk+-1.2 applications looked nice, and Aristotle had already said everything about politics that needs to be said).

  1. Harring Figueiredo shed some light on how GtkListStore and GtkTreeStore deal with pixbufs.
  2. Ken Rastatter suggested some additional topics (with complete references even).
  3. Both Andrej Prsa and Alan B. Canon sent me a couple of suggestions, and 'taf2', Massimo Mangoni and others spotted some typos.
  4. Many thanks to all of them, and of course also to kris and everyone else in #gtk+.

Original Revision History

14.3. Revision History

5th January 2008

  • Update some broken links; remove references to external cell renderers that have been obsoleted by Gtk adding such renderers.

5th June 2005

  • Remove unnecessary col = gtk_tree_view_column_new() im hello world code (leftover from migration to convenience functions).

3rd February 2005

  • Point out that GObjects such as GdkPixbufs retrieved with gtk_tree_model_get() need to be g_object_unref()'ed after use, as gtk_tree_model_get() adds a reference.
  • Added explicit (gint) event->x double to int conversion to code snippet using gtk_tree_view_get_path_at_pos() to avoid compiler warnings.

9th September 2004

  • Fixed another mistake in tree path explanation: text did not correspond picture (s/movie clips/movie trailers/); (thanks to Benjamin Brandt for spotting it).

6th August 2004

  • Fixed mistake in tree path explanation (s/4th/5th/) (thanks to both Andrew Kirillov and Benjamin Brandt for spotting it).

30th April 2004

  • Added Hello World

31st March 2004

  • Fixed fatal typo in custom list code: g_assert() in custom_list_init() should be ==, not != (spotted by mmc).
  • Added link to Owen Taylor's mail on the GtkTreeView Drag'n'Drop API.

24th January 2004

  • Fixed typo in code example (remove n-th row example) (Thanks to roel for spotting it).
  • Changed 'Context menus' section title

19th January 2004

  • Expanded section on GtkTreeRowReferences, and on removing multiple rows.

8th January 2004

  • Added tiny section on Glade and treeviews
  • Added more detail to the section describing GtkTreePath, GtkTreeIter et al.
  • Reformatted document structure: instead of one single chapter with lots of sections, have multiple chapters (this tutorial is way to big to become part of the Gtk+ tutorial anyway); enumerate chapters and sections.
  • Expanded the section on tree view columns and cell renderers, with help of two diagrams by Owen Taylor (from the GUADEC 2003 Gtk+ tutorial slides).

10th December 2003

  • Added more information about how to remove a single row, or more specifically, the n-th row of a list store
  • Added a short example about how to pack icons into the tree view.

28th October 2003

  • Editable cells will work fine even if selection is set to GTK_SELECTION_NONE. Removed sentences that say otherwise.

23rd October 2003

  • fix 'jumpy' selections in custom model GtkTreeSortable interface implementation. gtk_tree_model_rows_reordered() does not seem to work like the API reference implies (see bug #124790)
  • added section about how to get the cell renderer a button click happened on
  • added section about editable cells with spin buttons (and a CellRendererSpin implementation to the examples)

10th October 2003

  • make custom model GtkTreeSortable implementation emit "sort-column-changed" signal when sortid is changed
  • fixed code typo in selection function section; added a paragraph about rule hint to 'make whole row coloured or bold' section

7th October 2003

  • Reformatted source code to make it fit on pages when generating ps/pdf output
  • Added link to PDF and docbook XML versions.