Search code examples
pythonlistgtk3gtktreeview

Python - Gtk.TreeView with Gtk.ListStore get selected index


i want to store items in a gtk-list and i decided to use the Gtk TreeView as List. Because i am quite new to python and gtk i want to store my elements as string representation in the TreeView and in a seperate python-list the according objects.

So if i delete an item in the Gtk list (via key-event), i have to be able to determine the selected row index to delete the correct python-list element.

My actual question is: How can i determine the index of the selected row in a Gtk.TreeView?

Thank you for your help!

PS: I am using Python 3 with GTK 3


Solution

  • Use Gtk.TreeViewSelection. You can get it from Gtk.TreeView (Assuming you have id column in your GtkTreeModel (GtkListStore or GtkTreeStore) constructor).

        from gi.repository import Gtk
    
        def yourcallback ( selection ):
           model,list_iter = selection.get_selected ()
           if list_iter != None:
           # Debugging mode, uncomment to activate
           # print "row index = " + model[list_iter][column_number_that_you_want]
    
    
      # alternate
      # def yourcallback (path, column, data):
      #   ........
    
    
        ..........
        yourtvselection           = yourtv.get_selection ()        
        yourtvselection.connect ( "changed" , yourcallback)
        # alternative signal
        # yourtv.connect ("row-activated", yourcallback)