如何进行交互式搜索(通过按Ctrl-f或/调用搜索)来迭代Gtk.TreeView的折叠行?
例如,如果我想在以下代码中首先搜索“四分之二”而不扩展“第四行”:
from gi.repository import Gtk
class Main(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Recursive Search")
self.set_default_size(200, 200)
self.treestore = Gtk.TreeStore(str, str)
treeiter = self.treestore.append(None, ["Row One", ""])
self.treestore.append(treeiter, ["Row Two", "First in One"])
self.treestore.append(treeiter, ["Row Tree", "Second in One"])
treeiter = self.treestore.append(None, ["Row Four", ""])
self.treestore.append(treeiter, ["Row Five", "First in Four"])
self.treestore.append(treeiter, ["Row Six", "Second in Four"])
treeiter = self.treestore.append(None, ["Row Seven", ""])
self.treestore.append(treeiter, ["Row Eight", "First in Seven"])
self.treestore.append(treeiter, ["Row Nine", "Second in Seven"])
treeview = Gtk.TreeView(model=self.treestore)
renderer_text = Gtk.CellRendererText()
column_text = Gtk.TreeViewColumn(cell_renderer=renderer_text, text=0)
treeview.append_column(column_text)
column_text = Gtk.TreeViewColumn(cell_renderer=renderer_text, text=1)
treeview.append_column(column_text)
treeview.set_search_column(1)
treeview.set_headers_visible(False)
self.add(treeview)
win = Main()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
解决方法:
您可以使用Gtk.Treeview.set_search_equal_func():
def __init__(self):
...
treeview.set_search_equal_func(self.search_function)
self.treeview = treeview
def search_function(self, model, column, key, rowiter):
row = model[rowiter]
if key.lower() in list(row)[column-1].lower():
return False # Search matches
# Search in child rows. If one of the rows matches, expand the row so that it will be open in later checks.
for inner in row.iterchildren():
if key.lower() in list(inner)[column-1].lower():
self.treeview.expand_to_path(row.path)
break
else:
self.treeview.collapse_row(row.path)
return True # Search does not match
我会推荐gnome.org用于Gtk的文档.它没有所有最新的更新,但它具有许多Gtk类和函数的易于阅读和易于查找的文档.