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.
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:
- Get the selection object of the view (
gtk_tree_view_get_selection
) - Get the currently selected
GtkTreeIter
(gtk_tree_selection_get_selected
). - Aquire the next/previous iter (
gtk_tree_model_iter_next/previous
) - 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, ¤t);
if (gtk_tree_model_iter_next(model, ¤t))
gtk_tree_selection_select_iter(sel, ¤t);
}
(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)
来源:https://stackoverflow.com/questions/12883268/python-gtk3-treeview-move-selection-up-or-down