从 TreeView 中获取选定的对象

从 TreeView 中获取选定的对象

我一直在快速开发一款小型(首次)应用程序,但遇到了一个难题 - 如何从 TreeView 中获取选定的行(数据)?TreeView 的数据是从目录中的文件列表传递的,我需要知道选择了哪些行(以及选择了哪些文件)。最好的方法是什么?

这是当前的代码:

    self.treeview = self.builder.get_object("treeview")
    select = self.treeview.get_selection()
    select.connect("changed", self.on_tree_selection_changed)

def on_tree_selection_changed(selection):
    model, treeiter = self.treeview.selection-get()
    if treeiter != None:
        print "You selected", model[treeiter][0]

答案1

看这里:http://python-gtk-3-tutorial.readthedocs.org/en/latest/treeview.html

您可以通过将选择对象连接到事件来获取事件的选择:

select = tree.get_selection()
select.connect("changed", on_tree_selection_changed)
def on_tree_selection_changed(selection):
    model, treeiter = selection.get_selected()
    if treeiter != None:
        print "You selected", model[treeiter][0]

编辑:要在窗口类中进行设置,请使用以下代码:

class MyTreeView....
    ....Other Stuff...
        self.treeview = self.builder.get_object("treeview")
        select = self.treeview.get_selection()
        select.connect("changed", self.on_tree_selection_changed)

    def on_tree_selection_changed(self, selection):
        model, treeiter = selection.get_selected()
        if treeiter != None:
            print "You selected", model[treeiter][0]

编辑2:如果您想要选择多行,您需要使用返回所有选定行的实例Gtk.TreeSelection.get_selected_rows()列表。Gtk.TreePath

相关内容