Python - Gtk.TreeView 结合 Gtk.ListStore 获取选中索引

4 投票
1 回答
2002 浏览
提问于 2025-04-18 06:07

我想在一个gtk列表中存储一些项目,所以我决定用Gtk TreeView来做这个列表。因为我对python和gtk还很陌生,所以我想把我的元素以字符串的形式存储在TreeView中,而在一个单独的python列表中存储对应的对象。

这样,如果我在Gtk列表中删除一个项目(通过按键事件),我就需要能够确定被选中行的索引,以便删除正确的python列表中的元素。

我现在的问题是:我该如何确定Gtk.TreeView中选中行的索引?

谢谢你的帮助!

PS:我使用的是Python 3和GTK 3

1 个回答

5

使用 Gtk.TreeViewSelection。你可以从 Gtk.TreeView 中获取它(假设你在 GtkTreeModel(GtkListStore 或 GtkTreeStore)的构造函数中有一个 id 列)。

    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)

撰写回答