[wxPython-users] 回复: [wxPython-users] ListCtrl

James Bigler bigler at cs.utah.edu
Wed Nov 22 11:59:51 PST 2006


光华 陶 wrote:
> tell the listctrl which cloumns are numeric,  say num_cols=[1,5,6]
>   then:
>   ....
>   if col in num_cols:
>       value1 = float(value1)
>       value2 = float(value2)
>   ....
> I do sort numeric cloumns this way. 
> James Bigler <bigler at cs.utah.edu> 写道:
>   I'm going through chapter 13 from the wP in Action book and I'm wondering if 
> there is a way to get the sorting not by string but by some other method (such 
> as numerically). I'm looking at the code from list_report_colsort.py.
> 
> Thanks,
> James

I'm not sure what you had in mind, but this is how I did it.

I overrode the GetColumnSorter to choose which sorting function to use based on
the column being sorted.  I also added a new NumericalColumnSorter that cast the
arguments to floats and did a comparison.

Not the most efficient way of doing it, as I would like to store the numerical
values as floats instead of strings.  Suggestions are welcome.

As far at the demo code is concerned, I tested this by making some of the
numbers have fewer digits, so 8435 would be before 84200.

James

class DemoFrame(wx.Frame, wx.lib.mixins.listctrl.ColumnSorterMixin):
    def __init__(self):
        ...
        self.numericalColums = [0]
        ...

    # Override the parent function to choose which sorter to use.
    def GetColumnSorter(self):
        if self._col in self.numericalColums:
            return self.NumericalColumnSorter
        else:
            # Call the original one to get access to the private
            # version that handles strings.
            return wx.lib.mixins.listctrl.ColumnSorterMixin.GetColumnSorter(self)

    def NumericalColumnSorter(self, key1, key2):
        col = self._col
        ascending = self._colSortFlag[col]
        item1 = float(self.itemDataMap[key1][col])
        item2 = float(self.itemDataMap[key2][col])

        cmpVal = item1-item2

        # If the items are equal then pick something else to make the
        # sort value unique
        if cmpVal == 0:
            cmpVal = apply(cmp, self.GetSecondarySortValues(col, key1, key2))

        if ascending:
            return cmpVal
        else:
            return -cmpVal




More information about the wxpython-users mailing list