wxPython ListCtrlで昇順、降順のソートをしてみる
wx.ListCtrlで、表のタイトルの部分をクリックすると小さい順にソートし、もう1回クリックすると大きい順にソートしてみた。
Windowsのエクスプローラなんかをみると、正順、逆順にソートできるようになっていて便利なので、同じようにソートできるようにしてみた。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #!/usr/bin/env python #coding:utf-8 import wx caption = (u "No" ,u "都道府県" ,u "男女計" ,u "男" ,u "女" ) data = [ ( 1 ,u "北海道" , 5570 , 2638 , 2933 ), ( 2 ,u "青森県" , 1407 , 663 , 744 ), ( 3 ,u "岩手県" , 1364 , 652 , 712 ), ( 4 ,u "宮城県" , 2347 , 1140 , 1208 ), ( 5 ,u "秋田県" , 1121 , 527 , 593 ), ( 6 ,u "山形県" , 1198 , 575 , 623 ), ( 7 ,u "福島県" , 2067 , 1004 , 1063 ), ( 8 ,u "茨城県" , 2969 , 1477 , 1492 ), ( 9 ,u "栃木県" , 2014 , 1001 , 1013 ), ( 10 ,u "群馬県" , 2016 , 993 , 1024 ), ( 11 ,u "埼玉県" , 7090 , 3570 , 3520 ), ( 12 ,u "千葉県" , 6098 , 3047 , 3051 ), ( 13 ,u "東京都" , 12758 , 6354 , 6405 ), ( 14 ,u "神奈川県" , 8880 , 4484 , 4396 ), ] class MyTable(wx.ListCtrl): def __init__( self ,parent): wx.ListCtrl.__init__( self ,parent, - 1 ,style = wx.LC_REPORT | wx.LC_VIRTUAL) self .InsertColumn( 0 ,caption[ 0 ],wx.LIST_FORMAT_RIGHT) self .InsertColumn( 1 ,caption[ 1 ]) self .InsertColumn( 2 ,caption[ 2 ],wx.LIST_FORMAT_RIGHT) self .InsertColumn( 3 ,caption[ 3 ],wx.LIST_FORMAT_RIGHT) self .InsertColumn( 4 ,caption[ 4 ],wx.LIST_FORMAT_RIGHT) self .items = data self .SetItemCount( len ( self .items)) self .Bind(wx.EVT_LIST_COL_CLICK, self .Sort) self .prevColumn = None self .sortAcend = True def OnGetItemText( self ,line,col): return self .items[line][col] def Sort( self ,event): col = event.GetColumn() if col ! = self .prevColumn: self .sortAcend = True else : if self .sortAcend: self .sortAcend = None else : self .sortAcend = True if self .sortAcend: self .items.sort( lambda x,y: cmp (x[col],y[col])) else : self .items.sort( lambda x,y: cmp (y[col],x[col])) self .prevColumn = col self .DeleteAllItems() self .SetItemCount( len ( self .items)) class MyWindow(wx.Frame): def __init__( self ,parent, id ): wx.Frame.__init__( self , parent, id , u "ソートの実験" , size = ( 450 , 300 )) MyTable( self ) if __name__ = = '__main__' : app = wx.PySimpleApp() frame = MyWindow(parent = None , id = - 1 ) frame.Show() app.MainLoop() |