How to search through a gtk.ListStore in pyGTK and remove elements?

限于喜欢 提交于 2019-12-31 02:29:09

问题


I have the following code (where store is a gtk.ListStore and titer is a gtk.TreeIter. The docs say that if there is no next row, iter_next() will return None, hence the break when that is found. It is supposed to search through the ListStore of (int, str) and remove the one item whose int component matches item_id.

    while True:
        if store.get_path(titer)[0] == item_id:
            store.remove(titer)
            break
        else:
            titer = store.iter_next(titer)
            if titer is None:
                break

However, if an element in the middle has previously been deleted, instead of titer.iter_next() pointing to the next valid element, it points to None. This means that if the element with the right int value is after the previously deleted item, it never gets found. Is there a correct way to search through a gtk.ListStore to remove items?


回答1:


The only mistake I notice is store.get_path(titer)[0], which will just get the row number of the list model. It should be store.get_value(titer, 0).

By the way, your code can be expressed in a simpler style using the (PyGTK-only) TreeModelRow:

for row in store:
    if row[0] == item_id:
        store.remove(row.iter)
        break



回答2:


sanity check: make sure there is data in your list store when trying to search it

    column_number = 0
    search_term = 'foo'
    iter_child = tree_model.get_iter_first()
    tree_path = None
    while iter_child:
        if (tree_model.get_value(iter_child, column_number) == search_term):
            tree_path = tree_model.get_path(iter_child)
        iter_child = tree_model.iter_next(iter_child)

    view.row_activated(tree_path, column_number)
    view.set_cursor(tree_path, column_number, True)


来源:https://stackoverflow.com/questions/3426106/how-to-search-through-a-gtk-liststore-in-pygtk-and-remove-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!