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();
By default, only single rows can be selected, but you can allow multiple selection by setting the mode, like so:
refTreeSelection->set_mode(Gtk::SelectionMode::MULTIPLE);
For single-selection, you can just call get_selected()
,
like so:
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.
}
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)
);
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
}
To change the selection, specify a
Gtk::TreeModel::iterator
or
Gtk::TreeModel::Row
, like so:
auto row = m_refModel->children()[5]; //The sixth row.
if(row)
refTreeSelection->select(row.get_iter());
or
auto iter = m_refModel->children().begin()
if(iter)
refTreeSelection->select(iter);