1

我有一个gtk.ListStore附加到一个gtk.Treeview

第一列gtk.ListStorestr类型并且包含一个日期值(dd/mm HH:MM:SS)

我想gtk.TreeviewColumn按日期对第一个进行排序,所以我写道:

listStore = gtk.ListStore(str, str, str, str, str, str, str, str)
treeview = gtk.TreeView()
treeview.set_model(listStore)

cell = gtk.CellRendererText()
column = gtk.TreeViewColumn('Date', cell, text=0)
column.set_sort_column_id(0)
treeview.append_column(column)

但是排序不能正常工作:它按天排序,而不是按日期排序。

如何按日期进行排序?

谢谢

编辑 :

为了使排序更容易,月份值存储为数字(从 01 到 12)。

4

1 回答 1

0

我使用以下方法找到了解决方案Gtk.TreeSortable.set_sort_func()

listStore = gtk.ListStore(str, str, str, str, str, str, str, str)
listStore.set_sort_func(0, date_compare, None)
treeview = gtk.TreeView()
treeview.set_model(listStore)

cell = gtk.CellRendererText()
column = gtk.TreeViewColumn('Date', cell, text=0)
column.set_sort_column_id(0)
treeview.append_column(column)
...

我写了我的date_compare函数:

(也许它有一种最优雅的方式来编写这个date_compare函数:我很高兴听到你的:-))

def date_compare(model, row1, row2, user_data):
    # Returns : 
    # - a negative integer if iter1 sorts before iter2,
    # - zero if they are equal,
    # - a positive integer if iter2 sorts before iter1.

    sort_column, _ = model.get_sort_column_id()
    date1 = model.get_value(row1, sort_column)
    date2 = model.get_value(row2, sort_column)

    # We split the date string to an array : 
    #  0  |   1   |   2  |    3    |    4
    # day | month | hour | minutes | seconds
    values1 = re.split("[ /:]", date1)
    values2 = re.split("[ /:]", date2)

    if values1[1] < values2[1] :
        return -1
    elif values1[1] == values2[1] : # same month => we compare by day
        if values1[0] < values2[0] :
            return -1
        elif values1[0] == values2[0] : # same month and day => we compare by hour
            if values1[2] < values2[2] :
                return -1
            elif values1[2] == values2[2] : # same month, day and hour => we compare by minute
                if values1[3] < values2[3] :
                    return -1
                elif values1[3] == values2[3] : # same month, day, hour and minute => we compare by second
                    if values1[4] < values2[4] :
                        return -1
                    elif values1[4] == values2[4] : # same month, day, hour, minute and second => it's same date !
                        return 0
                    else :
                        return 1
                else :
                    return 1
            else :
                return 1
        else :
            return 1
    else :
        return 1
于 2012-04-04T14:23:43.753 回答