Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python GTK3 Treeview Move Selection up or down

How do I move a selection up or down in a Treeview?

The idea is that I can have an up and down buttons to move the selection up a row or down a row.

My Treeview is using a ListStore. Not sure if that matters.

like image 563
Samuel Taylor Avatar asked Feb 18 '23 20:02

Samuel Taylor


1 Answers

First off, I will be using C code as that's what I'm familiar with. Should you have problems translating it to Python, then say so, and I will do my best to help.

The class you want to use for this is GtkTreeSelection. Basically, what you do is:

  1. Get the selection object of the view (gtk_tree_view_get_selection)
  2. Get the currently selected GtkTreeIter (gtk_tree_selection_get_selected).
  3. Aquire the next/previous iter (gtk_tree_model_iter_next/previous)
  4. If there is one (ie. if the previous function returned true), make it the currently selected one (gtk_tree_selection_select_iter)

In my little test program, the callback for the "down" button looked like this:

static void on_down(GtkWidget *btn, gpointer user_data)
{
    GtkTreeSelection *sel = GTK_TREE_SELECTION(user_data);
    GtkTreeModel *model;
    GtkTreeIter current;

    gtk_tree_selection_get_selected(sel, &model, &current);
    if (gtk_tree_model_iter_next(model, &current))
        gtk_tree_selection_select_iter(sel, &current);
}

(here is the full program for reference)

When connecting, I passed the TreeSelection object to the callback.

Edit: This is how Samuel Taylor translated the above to Python:

TreeView = Gtk.TreeView()
list = Gtk.ListStore(str, str)
TreeView.set_model(list)

def down(widget):
    selection = TreeView.get_selection()
    sel = selection.get_selected()
    if not sel[1] == None:
        next = list.iter_next(sel[1])
        if next:
            selection.select_iter(next)
like image 100
Ancurio Avatar answered Feb 26 '23 19:02

Ancurio