Friday, 19 March 2021

GTK3 - Python Treeview Filter Function

I have a simple GTK3 GUI with a treeview and treestore. I need to filter the column with data3 string and show only data3 row. But it also hides data3 row. Because parent row of the data3 column is also hidden.

It works when I use return model[iter][2] == "data2" instead of return model[iter][2] == "data3".

All of the rows could be viewed by commenting out this line: filter1.set_visible_func(filter1_func)

How could I fix this?

Simplified code:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib

builder = Gtk.Builder()
builder.add_from_file('test.glade')
builder.get_objects()
window1 = builder.get_object('window1')
treeview1 = builder.get_object('treeview1')

class Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()

def filter1_func(model, iter, data):
    return model[iter][2] == "data3"

list_data = [["text1", "data1", "data2"], ["text2", "data1", "data2"], ["text3", "data1", "data3"]]

treestore1 = Gtk.TreeStore(str, str, str)
piter1 = treestore1.append(None, list_data[0])
piter2 = treestore1.append(piter1, list_data[1])
piter3 = treestore1.append(piter1, list_data[2])

treeview1.set_model(treestore1)
filter1 = treestore1.filter_new()
filter1.set_visible_func(filter1_func)
filter1.refilter()

for i, column_title in enumerate(["col1", "col2", "col3"]):
    renderer = Gtk.CellRendererText()
    column = Gtk.TreeViewColumn(column_title, renderer, text=i)
    treeview1.append_column(column)

treeview1.set_model(filter1)
treeview1.expand_all()

builder.connect_signals(Signals())
window1.show_all()
Gtk.main()


from GTK3 - Python Treeview Filter Function

No comments:

Post a Comment