Python:对 GTK 树视图进行排序

yPh*_*hil 1 python gtk pygtk

我不明白gtk.Treeview()列表模型是如何工作的:

据我所知,我必须将 lismodel 包装在 a 中,gtk.TreeModelSort()但是当我这样做时,我无法再访问 listmodel 方法了..

    lm = gtk.ListStore(object)
    listmodel = gtk.TreeModelSort(lm)
    for f in files:
        listmodel.append([f])
    return listmodel
Run Code Online (Sandbox Code Playgroud)

AttributeError: 'gtk.TreeModelSort' 对象没有属性 'append'

我正在使用这个示例源代码):如何使表格在每一列上都可排序?

vbr*_*aun 5

gtk.TreeModelSort只是一个模型(访问接口),它实际上并不存储任何东西。事实上,您不需要自己调用它来使您的表可排序。最简单的方法是让 GTK 为您进行排序,这意味着您必须在表中存储 C 数据而不是 Python 对象。所以,改变你的make_list()方法

listmodel = gtk.ListStore(str)
Run Code Online (Sandbox Code Playgroud)

而不是object. 然后你只需将告诉gtk.TreeView那个点击第一列标题排序应根据在第一列gtk.ListStore通过将

self.tvcolumn[0].set_sort_column_id(0)
Run Code Online (Sandbox Code Playgroud)

进入你的构造函数。要按文件大小排序,您需要int在列表存储中添加一个额外的列,并将其用作排序列 id 等。

编辑:好的,让我拼出最后一件事:

listmodel = gtk.ListStore(str, int)
for f in files:
    file_size = os.stat(os.path.join(self.dirname, f)).st_size
    listmodel.append([f, file_size])
Run Code Online (Sandbox Code Playgroud)

将文件大小放在存储​​的第二列中。然后,要按文件大小排序,您只需添加

self.tvcolumn[1].set_sort_column_id(1)
Run Code Online (Sandbox Code Playgroud)

一般来说,我建议重构您的代码,使所有内容ListStore在开始时都存储在一次中。这样,您只需将每个视图列绑定到商店列,就可以更轻松地对单元格渲染进行编码。