| FAQ Index - Search - Recent Changes - Everything - Add entry |
13.10. How do I make a GtkTreeView with editable cells?
This can be done two different ways:
1) Set the "editable" property to True for all the cells in a column:
renderer = gtk.CellRendererText()
renderer.connect('edited', cell_edited_callback)
renderer.set_property('editable', True)
treeview.insert_column_with_attributes(-1, 'Editable String', renderer, text=0)
or
2) Set the "editable" property to True for individual cells:
The first thing you have to do is include a column of type boolean. It will specify if a row is editable or not.
model = gtk.TreeStore(str, int, bool) iter = model.append() model.set_value(iter, 0, 'foo') model.set_value(iter, 1, 34) model.set_value(iter, 2, True)Next thing is create the TreeView, Columns and Renderers:
treeView = gtk.TreeView(model)
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('column 1', renderer, text=0, editable=2)
treeView.append_column(column)
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('column 2', renderer, text=1, editable=2)
treeView.append_column(column)
And that's all. The important thing is the creation of the column. The
values of the properties 'text' and 'editable' are column indexes of the
model. So in the first column we are saying that the text property of
the renderer should use the index 0 of the model and should use the
value of the index 2 for the editable property (which we set it to
gtk.TRUE when we added the row)
The process is similar for ToggleButtons, but the property names are different and you need to set up a callback for the toggle signal to make the changes persistent. So let's create a simple model:
model = gtk.ListStore(bool, bool) model.append(row=(True, True)) model.append(row=(False, False))This time the first value of the model holds the real data and we use the second boolean type for the 'activatable' status. Let's create the TreeView and the column:
treeview = gtk.TreeView(model)
renderer = gtk.CellRendererToggle()
renderer.connect('toggled', toggled_callback, model)
column = gtk.TreeViewColumn('test', renderer, active=0, activatable=1)
treeview.append_column(column)
As you can see we need to setup the toggle_callback, which looks like this:
def toggled_callback(cell, path, model=None):
iter = model.get_iter(path)
model.set_value(iter, 0, not cell.get_active())
This last step is important because otherwise the TreeView won't update the screen and it will look like a non activatable column.
- Note that the toggled_callback changes the model value for column 0. The path argument is actually the row number in the model. In a multi-column view, add a fourth argument to the renderer.connect call to pass the column to the callback. For example, if the ToggleButton is in column 2:
renderer.connect('toggled', toggled_callback, model, 1)
and update the callbacks declaration to:
def toggled_callback(cell, path, model=None, col_num=0):
