从 Gtk TreeStore 中删除多行

Removing multiple rows from a Gtk TreeStore

我正在尝试从 Gtk.TreeStore:

中删除多行
        data_selection = data_treeview.get_selection()
        data_model, data_row_list = data_selection.get_selected_rows()

        treeiter_list = []

        for treepath in data_row_list:
            row = data_model[treepath]
            treeiter_list.append(data_model.get_iter(row))

        for treeiter in treeiter_list:
            data_treestore.remove(treeiter)

如果我只 select 一行,这会起作用。一旦 select 超过一个,我就会收到此错误:

Gtk-CRITICAL **: gtk_list_store_remove: assertion 'iter_is_valid (iter, list_store)' failed

删除第一行后,treeiter是否失效?

Do the treeiters become invalid after the first row is deleted?

是的。如果删除一行,树路径也会改变。

关键是倒序删除树路径,所以路径仍然有效。也不要存储迭代器,而是使用路径并在循环内调用迭代器,不需要双循环。

例子的关键部分:

selection = self.view.get_selection()
model, paths = selection.get_selected_rows()
for p in reversed(paths):
    itr = model.get_iter(p)
    model.remove(itr)

完整示例可在以下位置找到:

https://gist.github.com/carlos-jenkins/c4fedad66169b75424a0

请注意,如果模型不是排序模型,这将起作用。如果是,您将需要致电 convert_iter_to_child_iter 以便删除它。

https://developer.gnome.org/gtk3/3.14/GtkTreeModelSort.html#gtk-tree-model-sort-convert-iter-to-child-iter