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

Filed under: Tutorials and HOWTOs by Hari
Posted at 08:33 IST (last updated: Tue, 25 May 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)

Leave a comment »
  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, 17 Sep 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, 17 Sep 2010 @ 20:44 IST #

Leave a comment

First-time comments on this blog are moderated.
Your name*
Email ID*
(wont' be published)
Website
Your comments*
(No HTML allowed)
:-) :-D :biggrin: :-P ;-) 8-) :-( :mad: |-| :oops: :-/ :-| :roll:
bold italic quote code
Code* captcha Enter the code you see in the image
* required fields