ListStore sorting and TreeIter row delete...



Hi all,

I'm new to this list, and to programming using gtkmm as well. I was
looking for a way to create a tree list with clickable sort columns,
but found nothing in the example code shipped with gtkmm. I finally
found an example, booklist.tar.gz, listed in a post on this list last
year (31 Jul 2004) (discovered via a Google search):

http://mail.gnome.org/archives/gtkmm-list/2004-July/msg00221.html

First of all, this example was a *great* help because I got to see how
to use the TreeModelSort object in tandem with the ListStore.

However, there was a spot in the code labelled "FIXME: This does not
work." Apparently, when you select a row and click the "delete"
button, gtkmm asserts with a VALID_ITER error.  I searched around the
list to see if the problem had been solved, but found no solution
posted. But, I might have missed it, so please forgive me is this is a
duplicate post.

For what it's worth, I found the problem and I wanted to share my
solution. Hopefully it will help out someone else like me.

Here it is:

The problem line in the code is in GtkBooklist.cc in the
remove_selected() method. The offending line is here:

store->erase(get_selection()->get_selected());

The get_selection() method returns a RefPtr<TreeSelection> object. The
TreeSelection::get_selected() method returns a TreeModel::iterator.
However, the problem here is that the iterator returned by
get_selected() above is not a ListStore iterator, so it's a mismatch.

The model assigned into the TreeView is of TreeModelSort, not of
ListStore (a ListStore object pointer was passed into the static
create() method of TreeModelSort instead). So the iterator returned by
TreeSelection::get_selected() above is an iterator of TreeModelSort,
not ListStore.  It just so happens that there is a handy
TreeModelSort::convert_iter_to_child_iter() method which we can use to
get the ListStore iterator. Once done, we can safely call the
"erase()" method on the ListStore object.

So the above line is replaced by the following code:

Gtk::TreeModel::iterator list_model_iter = 
   sortstore->convert_iter_to_child_iter( get_selection()->get_selected() );
store->erase( list_model_iter );

...and it works! Voila! :-)

Doug Barbieri

PS: I would really like to see the booklist example put into the gtkmm
example code downloadable from the gtkmm site. It would be a huge help
since sorting columns in a TreeView is a very common thing.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]