The Selection
| Chapter 9. The TreeView widget |

## The Selection

To find out what rows the user has selected, get the `Gtk::TreeView::Selection` object from the `TreeView`, like so:

    Glib::RefPtr<Gtk::TreeSelection> refTreeSelection =
        m_TreeView.get_selection();

### Single or multiple 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::SELECTION_MULTIPLE);

### The selected rows

For single-selection, you can just call `get_selected()`, like so:

    TreeModel::iterator iter = refTreeSelection->get_selected();
    if(iter) //If anything is selected
    {
      TreeModel::Row row = *iter;
      //Do something with the row.
    }

For multiple-selection, you need to 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::iterator& iter)
    {
      TreeModel::Row row = *iter;
      //Do something with the row.
    }

### The "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)
    );

### Preventing row selection

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 Gtk::TreeModel::iterator iter = model->get_iter(path);
      return iter->children().empty(); // only allow leaf nodes to be selected
    }

### Changing the selection

To change the selection, specify a `Gtk::TreeModel::iterator` or `Gtk::TreeModel::Row`, like so:

    Gtk::TreeModel::Row row = m_refModel->children()[5]; //The fifth row.
    if(row)
      refTreeSelection->select(row);

or

    Gtk::TreeModel::iterator iter = m_refModel->children().begin()
    if(iter)
      refTreeSelection->select(iter);

Iterating over Model Rows |  | Sorting