Hari's Corner

Humour, comics, tech, law, software, reviews, essays, articles and HOWTOs intermingled with random philosophy now and then

Python Gtk HOWTO: deleting multiple selected items from a gtk.TreeView

Filed under: Tutorials and HOWTOs by Hari
Posted on Tue, May 25, 2010 at 08:33 IST (last updated: Tue, May 25, 2010 @ 08:49 IST)

In this series < Previous
This is yet another simple HOWTO for personal reference, but I document this in the hope that it will be useful for others as well.

As I mentioned before, the gtk.TreeView widget is one of the most tortuous Gtk widgets ever created. Using and manipulating it involves quite a few non-obvious techniques. Here's the code to deleting multiple selected items in a gtk.TreeView widget.

In the below example the widgets are created by Glade/GtkBuilder so I call the get_object () method of the GtkBuilder object to get the widgets.
def remove_selected_items (self):
	# get the file treeview and liststore
	file_view = self.ui.get_object ("tree_files")
	file_list = self.ui.get_object ("filelist")
	# get the selected rows as paths
	sel_model, sel_rows = file_view.get_selection ().get_selected_rows ()
	# store the treeiters from paths
	iters = []
	for row in sel_rows:
		iters.append ( file_list.get_iter (row) )
	# remove the rows (treeiters)
	for i in iters:
		if i is not None:
			file_list.remove (i)

As you can see, it involves the following steps:
  1. Get the TreeSelection object associated with the TreeView and call get_selected_rows () to get the row model and selected paths.
  2. Convert each of the selected paths into TreeIters.
  3. Now call the method remove () method on each of the selected items in the ListStore or TreeModel object.

Note that directly trying to remove paths in the first step will lead to an error because once a path is deleted, the remaining paths might point to a non-existent node.

In this series

2 comment(s)

  1. Just used it.
    It works perfectly fine :)

    Thanks a lot for sharing that !
    Clearly treemodel are quite a pain in the a** to manipulate.

    Comment by TeT (visitor) on Fri, Sep 17, 2010 @ 20:13 IST #
  2. Glad you found it useful, TeT. Yes, GTK is a bit awkward compared to Qt because of its design.

    Comment by Hari (blog owner) on Fri, Sep 17, 2010 @ 20:44 IST #

Comments closed

The blog owner has closed further commenting on this entry.