Sortering

Standardträdmodellerna (TreeStore och ListStore) härleds från TreeSortable, så de erbjuder funktionalitet för sortering. Anropa exempelvis set_sort_column() för att sortera modellen efter angiven kolumn. Eller tillhandahåll en återanropsfunktion till set_sort_func() för att implementera en mer komplicerad sorteringsalgoritm.

Referens för TreeSortable

Sortering genom att klicka på kolumner

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

auto pColumn = treeview.get_column(0);
if(pColumn)
  pColumn->set_sort_column(m_columns.m_col_id);

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::TreeViewColumn::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:

auto sorted_model = Gtk::TreeModelSort::create(model);
sorted_model->set_sort_column(columns.m_col_name, Gtk::SortType::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()
{
  auto refTreeSelection = m_treeview.get_selection();
  if(refTreeSelection)
  {
    auto sorted_iter = m_refTreeSelection->get_selected();
    if(sorted_iter)
    {
      auto iter = m_refModelSort->convert_iter_to_child_iter(sorted_iter);
      m_refModel->erase(iter);
    }
  }
}

Referens för TreeModelSort