Search code examples
pythonpython-3.xgtk3

Cannot sort columns in Gtk.TextView i Python 3


When I try to make my Gtk.TreeView in Python sortable by column I use something like

for i, column_title in enumerate(["Title A", "Title B"]):
    renderer = Gtk.CellRendererText()
    column = Gtk.TreeViewColumn(column_title, renderer, text=i)
    column.set_sort_indicator(True)
    column.set_sort_order(Gtk.SortType.ASCENDING)
    column.set_sort_column_id(i)  # trying to make columns sortable
    self.study_view.append_column(column)

but when I click on the title of a column I get the error message

(main.py:14540): Gtk-CRITICAL **: 22:46:43.573: gtk_tree_sortable_get_sort_column_id: assertion 'GTK_IS_TREE_SORTABLE (sortable)' failed

I've googled the problem but haven't found a solution. The docs give no hint. What's wrong?

Here's the line in the complete Python application the gives the error message:

https://github.com/nordlow/dicom/blob/master/main.py#L241

I'm using these docs as a reference:

https://python-gtk-3-tutorial.readthedocs.io/en/latest/treeview.html?highlight=view#sorting


Solution

  • This is one of the more complicated pieces of machinery in Gtk. You need to wrap the filtered TreeModel with a sorted model, so that you can sort the filtered model again. Note that a plain TreeModel is sortable before you wrap it with a filtered model. So your code should look like this on line 225:

    self.study_store = StudyStore(client=self.client)
    self.current_study_filter = None
    self.study_filter = self.study_store.filter_new()
    self.study_filter.set_visible_func(self.study_view_filter_func)
    self.study_sort = Gtk.TreeModelSort(self.study_filter)
    self.study_view = Gtk.TreeView.new_with_model(self.study_sort)
    

    P.S. I think you are overusing class variables. No offense please.