2017-09-01 35 views
0

如何調整ListEditor以使用TraitsUI列出任意集合的內容?下面是一個示例代碼使用TraitsUI ListEditor Factory進行任意集合

from traits.api import HasStrictTraits, Instance, Int, List, Str 
from traitsui.api import View, Item, ListEditor, InstanceEditor 

from sortedcontainers import SortedListWithKey 

class Person(HasStrictTraits): 
    name = Str 
    age = Int 

class Office(HasStrictTraits): 
    # employees = Instance(SortedListWithKey, 
          kw={'key': lambda employee: employee.age}) 
    employees = List 

employee_view = View(
    Item(name='name', show_label=False, style='readonly') 
) 

office_view = View(
    Item(name='adults', 
     show_label=False, 
     style='readonly', 
     editor=ListEditor(
      style='custom', 
      editor=InstanceEditor(view=employee_view), 
     ), 
    ), 
    resizable=True 
) 

employee_list = [Person(name='John', age=31), Person(name='Mike', age=31), 
       Person(name='Jill', age=37), Person(name='Eric', age=28)] 

#office = Office() 
#office.employees.update(employee_list) 
office = Office(employees=employee_list) 

office.configure_traits(view=office_view) 

如果我用我註釋掉的代碼替換SortedListWithKey標準的名單,我得到「AttributeError的:‘辦公室’對象有沒有屬性‘值’」的錯誤。我該如何解決這個問題?

回答

1

性狀用來存儲在List特質任何一個list子類(TraitListObject):這是允許的性狀事件要在列表中更改項目,以及在屬性解僱。我猜SortedListWithKey類來自「Sorted Containers」第三方包,因此不是Traits列表。 ListEditor預計TraitsListObject(或類似工作)可以正常工作,因爲它需要知道列表項是否已更改。

修復/我能想到的變通辦法:

  1. 使用兩個List特質,一個無序(這可能是一個Set)和一個排序,並有特點的變化處理兩個同步。如果您的無序數據是「模型」圖層的一部分,並且其排序方式是面向用戶的「視圖」或「展示」層的一部分(即可能位於TraitsUI ControllerModelView對象中) )。

  2. 編寫TraitListObject的子類,其自我分類行爲爲SortedListWithKey。使用常規的List特徵,但將子類的實例分配給它,或者對於真正的浮動行爲子類List在任何集合操作上進行轉換到您的新子類。

  3. 使用常規的List特質,但對於nameageTableEditor:這是您打算什麼不同的UI,並且可能不適合你的真實世界是什麼,但TableEditor可以設置在列上自動排序。對於更簡單的例子,ListStrEditor也可能工作。

  4. 將功能添加到TraitsUI ListEditor,以便可以按排序順序顯示列表項。這可能是最困難的選擇。

雖然它顯然是最不優雅的解決方案,但我可能只是在大多數情況下與第一個解決方案。您也可以考慮在ETS-Users羣組上發佈此問題,以查看是否有其他人對此有任何想法。

+0

澄清:在我看來,排序不僅僅是一種觀點,而是「業務邏輯」的一部分。你說得對,'SortedListWithKey'來自「Sorted Containers」包。 – MindV0rtex