3.8. Storing GObjects (Pixbufs etc.)

A special case are GObject types, like GDK_TYPE_PIXBUF, that get stored in a list or tree store. The store will not make a copy of the object, rather it will increase the object's refcount. The store will then unref the object again if it is no longer needed (ie. a new object is stored in the old object's place, the current value is replaced by NULL, the row is removed, or the store is destroyed).

From a developer perspective, this means that you need to g_object_unref an object that you have just added to the store if you want the store to automatically dispose of it when no longer needed. This is because on object creation, the object has an initial refcount of 1, which is "your" refcount, and the object will only be destroyed when it reaches a refcount of 0. Here is the life cycle of a pixbuf:


  GtkListStore *list_store;
  GtkTreeIter   iter;
  GdkPixbuf    *pixbuf;
  GError       *error = NULL;

  list_store = gtk_list_store_new (2, GDK_TYPE_PIXBUF, G_TYPE_STRING);

  pixbuf = gdk_pixbuf_new_from_file("icon.png", &error);

  /* pixbuf has a refcount of 1 after creation */

  if (error)
  {
    g_critical ("Could not load pixbuf: %s\n", error->message);
    g_error_free(error);
    return;
  }

  gtk_list_store_append(list_store, &iter);

  gtk_list_store_set(list_store, &iter, 0, pixbuf, 1, "foo", -1);

  /* pixbuf has a refcount of 2 now, as the list store has added its own reference */

  g_object_unref(pixbuf);

  /* pixbuf has a refcount of 1 now that we have released our initial reference */

  /* we don't want an icon in that row any longer */
  gtk_list_store_set(list_store, &iter, 0, NULL, -1);

  /* pixbuf has automatically been destroyed after its refcount has reached 0.
   *  The list store called g_object_unref() on the pixbuf when it replaced
   *  the object in the store with a new value (NULL). */

Having learned how to add, manipulate, and retrieve data from a store, the next step is to get that data displayed in a GtkTreeView widget.