Search code examples
pythongtk4

How to get/set selected items of GTK4's ColumnView?


I'm trying to replace Gtk.TreeView with Gtk.ColumnView

for Gtk.TreeView (with Gtk.TreeStore) I have following code to get/set selection:

# get selection
selection = <my Gtk.TreeView>.get_selection()
model, treeiter = selection.get_selected_rows()
selected_items = []

for path in treeiter:
    treeiter = model.get_iter(path)
    value = model.get_value(treeiter, 0)
    selected_items.append(value)

print(selected_items)
# set selection
selection = <my Gtk.TreeView>.get_selection()
model, treeiter = selection.get_selected_rows()

for path in treeiter:
    treeiter = model.get_iter(path)
    value = model.get_value(treeiter, 0)

    if <my function that decides whether to select or not>(value):
        selection.select_iter(treeiter)
    else:
        selection.unselect_iter(treeiter)

How can i achieve the same thing with Gtk.ColumnView? Currently my code looks like this:

store = Gio.ListStore()
view = Gtk.ColumnView()
sel = Gtk.MultiSelection.new(self.store)

view.set_model(sel)
        
factory = Gtk.SignalListItemFactory()
factory.connect("bind", lambda _fact, item: item.set_child(Gtk.Label(halign=Gtk.Align.START, label=item.get_item())) )            
col_f = Gtk.ColumnViewColumn(title="Name",factory=factory)
view.append_column(col_f)

# how to get the Gtk.SelectionModel ??

I think I just need to somehow get Gtk.SelectionModel but how?


Solution

  • I finally figured out how to achieve it. Here is what did:

    # get selection
    selected_items = []
    
    for i in range(store.get_n_items()):
        if view.get_model().is_selected(i):
            selected_items.append(view.get_model().get_item(i))
    
    print(selected_items)
    
    # set selection
    for i in range(store.get_n_items()):
        value = view.get_model().get_item(i)
        if <my function that decides whether to select or not>(value):
            view.get_model().select_item(i)
        else:
            view.get_model().unselect_item(i)