如何使用TraitsUI修改ListEditor以列出任意集合的内容?下面是一个示例代码
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:'Office‘对象没有’value‘属性的错误。我该如何解决这个问题?
发布于 2017-09-03 17:26:24
对于存储在List特征中的任何内容,特征都使用一个list子类(TraitListObject):这就是允许特征事件在列表中的项以及属性发生变化时被激发的原因。我猜测SortedListWithKey类来自“排序容器”第三方包,因此不是一个特征列表。ListEditor需要一个TraitsListObject (或类似的工作)才能正常工作,因为它需要知道列表项是否发生了更改。
我能想到的修复/变通方法:
List特征,一个是未排序的(可能是Set),另一个是排序的,并具有特征更改处理程序来同步这两个特征。如果您的无序数据是“模型”层的一部分,并且它的排序方式是面向用户的“视图”或“表示”层的一部分(即。可能在TraitsUI Controller或ModelView ModelView中TraitListObject的一个子类,它具有SortedListWithKey的自排序行为。使用常规的List特征,但将子类的实例分配到它中,或者为了真正灵活的行为,子类List可以在任何集合上转换为新的子类。List特征是常规的List特征,但TableEditor包含name和age的列:这是一个与您想要的UI不同的UI,可能不适合您的实际情况,但是TableEditor可以设置为按列自动排序。对于更简单的示例,ListStrEditor也可以工作。ListEditor中,以便可以选择按排序顺序显示列表项。这可能是最困难的选择。虽然这显然是最不优雅的解决方案,但在大多数情况下,我可能只会选择第一种。你也可以考虑将这个问题发布在ETS-Users组上,看看其他人是否对此有一些想法。
https://stackoverflow.com/questions/46006127
复制相似问题