Die Auswahl
To find out what rows the user has selected, get the Gtk::TreeView::Selection object from the TreeView, like so:
auto refTreeSelection = m_TreeView.get_selection();
- 10.4.1. Einfache oder mehrfache Auswahl
- 10.4.2. Die ausgewählten Zeilen
- 10.4.3. Das »changed«-Signal
- 10.4.4. Verhindern der Zeilenauswahl
- 10.4.5. Ändern der Auswahl
10.4.1. Einfache oder mehrfache Auswahl
By default, only single rows can be selected, but you can allow multiple selection by setting the mode, like so:
refTreeSelection->set_mode(Gtk::SELECTION_MULTIPLE);
10.4.2. Die ausgewählten Zeilen
Für Einfachauswahlen können Sie einfach get_selected() folgendermaßen aufrufen:
auto iter = refTreeSelection->get_selected(); if(iter) //If anything is selected { auto row = *iter; //Do something with the row. }
For multiple-selection, you need to call get_selected_rows() or define a callback, and give it to selected_foreach(), selected_foreach_path(), or selected_foreach_iter(), like so:
refTreeSelection->selected_foreach_iter( sigc::mem_fun(*this, &TheClass::selected_row_callback) ); void TheClass::selected_row_callback( const Gtk::TreeModel::const_iterator& iter) { auto row = *iter; //Do something with the row. }
10.4.3. Das »changed«-Signal
To respond to the user clicking on a row or range of rows, connect to the signal like so:
refTreeSelection->signal_changed().connect( sigc::mem_fun(*this, &Example_IconTheme::on_selection_changed) );
10.4.4. Verhindern der Zeilenauswahl
Maybe the user should not be able to select every item in your list or tree. For instance, in the gtk-demo, you can select a demo to see the source code, but it doesn't make any sense to select a demo category.
To control which rows can be selected, use the set_select_function() method, providing a sigc::slot callback. For instance:
m_refTreeSelection->set_select_function( sigc::mem_fun(*this, &DemoWindow::select_function) );
and then
bool DemoWindow::select_function( const Glib::RefPtr<Gtk::TreeModel>& model, const Gtk::TreeModel::Path& path, bool) { const auto iter = model->get_iter(path); return iter->children().empty(); // only allow leaf nodes to be selected }
10.4.5. Ändern der Auswahl
Um die Auswahl zu ändern, geben Sie einen Gtk::TreeModel::iterator oder Gtk::TreeModel::Row folgendermaßen an:
auto row = m_refModel->children()[5]; //The sixth row. if(row) refTreeSelection->select(row.get_iter());
oder
auto iter = m_refModel->children().begin() if(iter) refTreeSelection->select(iter);