Get values from multiselect TreeView

Hi,
I’m trying to retrieve the values ​​of selected rows from a TreeView, but I’m having trouble (Gtkmm/Gtk4.6.9).

This is how I declared my TreeView:

  Gtk::TreeView m_TreeView;
  class ModelColumns : public Gtk::TreeModel::ColumnRecord {
  public:
    ModelColumns()
    { add(m_col_name);}
    Gtk::TreeModelColumn<Glib::ustring> m_col_name;
  };
  ModelColumns m_Columns;

In “Gtk::SelectionMode::SINGLE” mode I get the selected value like this:

  Glib::RefPtr<Gtk::TreeSelection> selection = m_TreeView.get_selection();
  Gtk::TreeModel::iterator selectedRow = selection->get_selected();
  Gtk::TreeModel::Row row = *selectedRow;
  Glib::ustring name = row.get_value(m_Columns.m_col_name);
  std::cout << "name: " << name<< std::endl;

On the other hand, I don’t know how to do it in “Gtk::SelectionMode::MULTIPLE” mode. I can loop over the selected lines, but how can I retrieve the values?

  Glib::RefPtr<Gtk::TreeSelection> selection = m_TreeView.get_selection();
  std::vector<Gtk::TreeModel::Path> selected_rows = selection->get_selected_rows();
  std::vector<Gtk::TreeModel::Path>::iterator TreePath_iterator = selected_rows.begin();

  while(TreePath_iterator != selected_rows.end())
  {
    Glib::ustring out_name; // == ???
    std::cout << "TreePath_iterator: " << out_name << std::endl;
    TreePath_iterator++;
  }

Thanks in advance.

If you haven’t gotten too far along, I’d strongly recommend considering the newer GtkListView widget. GtkTreeView is deprecated as of GTK 4.10.

In C, you would use gtk_tree_model_get_iter() to get a GtkTreeIter, and then gtk_tree_model_get() to get the value.

I don’t actually know C++, but I think it would look something like this:

for (auto path : selected_rows)
{
    auto row = *(m_TreeView.get_model()->get_iter(path));
    Glib::ustring out_name = row[m_Columns.m_col_name];
}
1 Like

Thanks, it works. Actually, I knew that GtkTreeView was deprecated since GTK 4.10 but I wanted to continue with this example, just to move forward with other parts of my code. I’m going to switch to the GtkListView widget.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.