GtkTreeView过滤和选择

时间:2015-06-15 11:36:42

标签: treeview pygtk gtk3

我有一个简单的GtkTreeView和一个GtkEntry用于过滤模型。 当我在条目中输入somehing时,software_list会按语言过滤。

software_list = [("Firefox", 2002,  "C++"),
                 ("Eclipse", 2004, "Java" ),
                 ("Netbeans", 1996, "Java"),
                 ("Chrome", 2008, "C++"),
                 ("GCC", 1987, "C"),
                 ("Frostwire", 2004, "Java")]

class TreeViewFilterWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)
        self.curr_filter = ''

        self.entry = Gtk.Entry()
        self.entry.connect('changed', self.on_text_change)

        self.software_liststore = Gtk.ListStore(str, int, str)
        for software_ref in software_list:
            self.software_liststore.append(list(software_ref))

        self.filter = self.software_liststore.filter_new()
        self.filter.set_visible_func(self.filter_func)

        self.treeview = Gtk.TreeView.new_with_model(self.filter)
        for i, column_title in enumerate(["Software", "Release Year", "Programming Language"]):
            renderer = Gtk.CellRendererText()
            column = Gtk.TreeViewColumn(column_title, renderer, text=i)
            self.treeview.append_column(column)
        self.treeview.get_selection().connect('changed', self.on_row_select) 

        # packing into boxes, showing components, starting main loop goes here

    def on_text_change(self, entry):
        self.curr_filter = entry.get_text()
        self.filter.refilter()

    def filter_func(self, model, iter, data):
        if self.curr_filter:
            return re.search(re.escape(self.curr_filter), model[iter][2])
        else:
            return True

问题是,当我选择" Chrome"从列表中键入" Java"然后,显然," Chrome"隐藏但选择更改为其他一些随机行。我更喜欢TreeView未选择的隐藏元素,而不是更改选择。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

这只是在Gtk2中按预期工作,但在Gtk3中,如果它消失,则需要取消选择该行。适当的代码是

class TreeViewFilterWindow(Gtk.Window):

    def __init__(...):
        ...
        self.selection = self.treeview.get_selection()
        self.filter.connect('row-deleted', self.on_row_deleted)

    def on_row_deleted(self, model, path):
        if self.selection.path_is_selected(path):
            GObject.idle_add(self.selection.unselect_path, path)

我发现直接调用self.selection.unselect_path(path)似乎并不是出于某种原因,但是将其推迟idle_add将其排除。