Sorting

The standard tree models (TreeStore and ListStore) derive from TreeSortable, so they offer sorting functionality. For instance, call set_sort_column(), to sort the model by the specified column. Or supply a callback function to set_sort_func() to implement a more complicated sorting algorithm.

TreeSortable Reference

9.5.1. Sorting by clicking on columns

So that a user can click on a TreeView's column header to sort the TreeView's contents, call Gtk::TreeViewModel::set_sort_column(), supplying the model column on which model should be sorted when the header is clicked. For instance:

Gtk::TreeView::Column* pColumn = treeview.get_column(0);
if(pColumn)
  pColumn->set_sort_column(m_columns.m_col_id);

9.5.2. Independently sorted views of the same model

The TreeView already allows you to show the same TreeModel in two TreeView widgets. If you need one of these TreeViews to sort the model differently than the other then you should use a TreeModelSort instead of just, for instance, Gtk::TreeViewModel::set_sort_column(). TreeModelSort is a model that contains another model, presenting a sorted version of that model. For instance, you might add a sorted version of a model to a TreeView like so:

Glib::RefPtr<Gtk::TreeModelSort> sorted_model =
    Gtk::TreeModelSort::create(model);
sorted_model->set_sort_column(columns.m_col_name, Gtk::SORT_ASCENDING);
treeview.set_model(sorted_model);

Note, however, that the TreeView will provide iterators to the sorted model. You must convert them to iterators to the underlying child model in order to perform actions on that model. For instance:

void ExampleWindow::on_button_delete()
{
  Glib::RefPtr<Gtk::TreeSelection> refTreeSelection =
      m_treeview.get_selection();
  if(refTreeSelection)
  {
    Gtk::TreeModel::iterator sorted_iter =
        m_refTreeSelection->get_selected();
    if(sorted_iter)
    {
      Gtk::TreeModel::iterator iter =
          m_refModelSort->convert_iter_to_child_iter(sorted_iter);
      m_refModel->erase(iter);
    }
  }
}

TreeModelSort Reference