按日期值排序gtk.TreeColumn

时间:2012-04-04 13:10:21

标签: python sorting gtk pygtk gtktreeview

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

gtk.ListStore的第一列属于str类型且包含日期值(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)。

1 个答案:

答案 0 :(得分: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