Create  Edit  FrontPage  Index  Search  Changes  History  RSS  Login

tips_lazy_treeview

Creating a "lazy" TreeView

In some applications, populating an entire tree of data to be displayed by a Gtk::TreeView can be expensive to do all at once. Thankfully it is possible to create a signal handler that populates child rows as they are expanded. The trick is to get the row expander to appear without any real child rows. The easiest way to achieve this is to create a "dummy" row which contains no data.

For example, let's create a simple TreeStore, and add a single row to it.

store = Gtk::TreeStore.new(String)
view = Gtk::TreeView.new(store)
column = Gtk::TreeViewColumn.new("Example column", 
                                  Gtk::CellRendererText.new, {:text => 1})

iter = store.append(nil)
iter[0] = 'Parent row'
store.append(iter)         # DUMMY CHILD

Then we can create a "row-expanded" handler which checks whether the first child row contains a real value; if it doesn't, we will append the actual data.

view.signal_connect("row-expanded") do |self, iter, path|
  child = iter.first_child
  if (! child[0])
    new_child = store.append(iter)
    new_child[0] = 'Child row'
    store.remove(child)    # REMOVE DUMMY CHILD 
  end
end

The order here is important. If you remove the dummy child before you append real data, the row will end up with no children and it will never expand.

Masao wrote a simple file tree browser that demonstrates a practical use of this technique: fileview.rb

ChangeLog

2003-10-21 Matthew Berg
Added ChangeLog
2003-10-20 Matthew Berg
Terminology corrections
2003-10-20 Matthew Berg
Initial release
Last modified:2014/08/04 06:46:17
Keyword(s):
References:[tips]