A sorted and filtered treemodel in Python Gtk+3..?

2020-06-18 03:22发布

问题:

I am trying to get a treemodel (a liststore in fact) that can be filtered and also sorted. I have the following piece of code

self.modelfilter = self.liststore.filter_new()
self.modelfilter.set_visible_func(\
            self._visible_filter_function)
self.treeview.set_model(self.modelfilter)

where self.liststore and self.treeview are standard Gtk.ListStore and Gtk.TreeView objects that I get from a glade file, and self._visible_filter_function is a filtering function.

The problem is that self.modelfilter does not seem to be sortable. When I click on the column headers (of the columns in self.treeview) to sort them, I get

Gtk-CRITICAL **: gtk_tree_sortable_get_sort_column_id: assertion `GTK_IS_TREE_SORTABLE (sortable)' failed

saying that the treemodel is not sortable.

This problem seems to be surmountable in PyGtk as suggested here. The idea is to stack a ListStore, a TreeModelFilter and a TreeSortFilter one inside the other and feed the last one as the model for the treeview.

However this trick does not seem to be working in Python Gtk+3. When I try

self.modelfilter = self.liststore.filter_new()
self.modelfilter.set_visible_func(\
            self._visible_filter_function)
self.sorted_and_filtered_model = \
            Gtk.TreeModelSort(self.modelfilter)
self.treeview.set_model(self.sorted_and_filtered_model)

it complains

Gtk.TreeModelSort(self.modelfilter)
TypeError: GObject.__init__() takes exactly 0 arguments (1 given)

Now I tried to get a instance of Gtk.TreeModelSort with no arguments. But this instance does not have any set_model method.

I am lost here.

Is there another way to set the model for Gtk.TreeModelSort? Or is there a totally different way to get a filtered and sortable treemodel object that can be displayed in a treeview?

回答1:

>>> from gi.repository import Gtk
>>> mymodel = Gtk.ListStore()
>>> Gtk.TreeModelSort(model=mymodel)
<TreeModelSort object at 0x1d4d190 (GtkTreeModelSort at 0x1f0d3f0)>

In my opinion PyGObject is not ready yet. It has no browsable documentation, some things are not instrospected yet and in particular this:

  • Sometimes a widget work with Gtk.MyWidget(attr=foo), like this one.
  • Sometimes with Gtk.MyWidget.new_with_label('Foo'), like buttons. Yes, Gtk.MyWidget(label='Foo') doesn't work.

Kind regards