FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 13.48 | Next Entry >>

13.48. How do I hide some rows in a TreeView?

To be able to hide some of the rows of a TreeView, you need to use a TreeModelFilter. This class acts as a wrapper for your TreeModel (a ListStore or TreeStore), allowing you to choose which rows are displayed based on the value of a gobject.TYPE_BOOLEAN column, or based on the output of a certain function.

Keep in mind that this is only a wrapper, it does not implement the usual insertion or removing functions provided by ListStore or TreeStore. To do that, you need to access the model itself.

Also, when you get an iter from your TreeView, it will point to the TreeModelFilter, so you need to make a translation into a useful iter, by calling convert_iter_to_child_iter(), and viceversa. The same goes for paths.

Here is a working example of how to create a TreeModelFilter to hide some rows, and how to access the data after it's been displayed.

 import gtk
 import gobject

 # Prepare the window and other Gtk stuff 
 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
 window.set_default_size(100, 200)
 window.connect("destroy", gtk.main_quit)
 vbox = gtk.VBox()
 window.add(vbox)

 # Creation of the actual model
 text = ["This", "is", "an", "example", "of", "hiding", "rows"]
 store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_BOOLEAN)
 for i in text:
    store.append((i, True))

 # Creation of the filter, from the model
 filter = store.filter_new()
 filter.set_visible_column(1)

 # The TreeView gets the filter as model
 view = gtk.TreeView(filter)

 # Some other gtk stuff
 renderer = gtk.CellRendererText()
 view.insert_column_with_attributes(-1,"Test",renderer,text=0)
 vbox.pack_start(view)
 hide_button = gtk.Button("Hide Selected")
 vbox.pack_start(hide_button)

 # The hiding function
 def hide_row(widget, *args):
    # Get the selected row
    filter_iter = view.get_selection().get_selected()[1]
    # Translate it into a useful iterator
    store_iter = filter.convert_iter_to_child_iter(filter_iter)
    # Use it to hide the row
    store[store_iter][1] = False

 hide_button.connect("clicked", hide_row)

 # That's it
 window.show_all()
 gtk.main()

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org