I already know that this post will be useful just to me, because I know that someday I’ll forgot how to do this and I’ll be looking for a solution. So here’s how to insert an image in a TreeView ListView using python.
Technically, a ListView widget doesn’t exists, but it is a TreeView with a ListStore model associated in place of a TreeModel. And this “howto” uses a ListView as example as it is easier to set up, but the concept remains the same for all the kind of TreeViews.
First thing: a TreeView (ehm, ListView) in gtk is made up by TreeViewColumns and CellRendererers of various type, according to what you want to display. But the first thing to do is to import the needed pygtk’s modules.
import pygtk
pygtk.require("2.0")
import gtk
import gobject
Then we must set up a model for our ListView and associate it to the newly created TreeView object, before than building it with columns:
treeview = gtk.TreeView()
model = gtk.ListStore(
gobject.TYPE_STRING, # a column will contain a string
gtk.gdk.Pixbuf) # and another column will contain our image
treeview.set_model(model)
After we done this, we must create the columns and the cells. A cell, under the gtk point of view, is every single place in the TreeView where a value can be inserted, that is every intersection of a row with a column. While the column are created using nearly always the same funtion (gtk.TreeViewColumn()), the cells aren’t. They have a different function according to the type of data you intend to show.
In our example we’ll use two functions: gtk.CellRendererText() and gtk.CellRendererPixbuf(). The former is used to render text items, while the latter for “images”.
So, after we created the model, we must create the columns and associate the cells to them. This is done by using the following code (in this example we’ll create a text column):
cell_text = gtk.CellRendererText()
col_text = gtk.TreeViewColumn("A text column", cell_text, text = 0)
treeview.append_column(col_text)
In this way we created a text-rendered column. The important part of the example is on the second line, when we set the text attribute with text = 0. Doing this we said to gtk to render a text column on the first column (0, not 1, because the numbering starts from 0). Now it’s time to show how to show an image, instead. This is done in a very similar way:
cell_img = gtk.CellRendererPixbuf()
col_img = gtk.TreeViewColumn("An image!", cell_img, pixbuf = 1)
treeview.append_column(col_img)
The only different thing is that, this time, we specified a pixbuf attribute in place of a text one.
Now that we created our treeview, we must add rows to it:
item = model.append(None)
model.set_value(item, 0, "Hey, I'm text!")
model.set_value(item, 1, gtk.gdk.pixbuf_new_from_file("/path/to/image.jpg")
The important thing to remember is that we must pass a gtk.gdk.Pixbuf object as image. That’s all :)
0 Comments.