Debian Codegraph @

traitsui/examples/demo/Advanced/Property_List_demo.py

raw
1 # (C) Copyright 2004-2023 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10
11 """
12 This demo shows the proper way to create a **Property** whose value is a
13 list, especially when the value of the **Property** will be used in a user
14 interface, such as with the **TableEditor**.
15
16 Most of the demo is just the machinery to set up the example. The key thing to
17 note is the declaration of the *people* trait:
18
19 people = Property( List, observe = 'ticker' )
20
21 In this case, by defining the **Property** as having a value of type
22 **List**, you are ensuring that the computed value of the property will be
23 validated using the **List** type, which in addition to verifying that the
24 value is indeed a list, also guarantees that it will be converted to a
25 **TraitListObject**, which is necessary for correct interaction with various
26 Traits UI editors in a user interface.
27
28 Note also the use of the *observe* metadata to trigger a trait property
29 change whenever the *ticker* trait changes (in this case, it is changed
30 every three seconds by a background thread).
31
32 Finally, the use of the *@cached_property* decorator simplifies the
33 implementation of the property by allowing the **_get_people** *getter*
34 method to perform the expensive generation of a new list of people only when
35 the *ticker* event fires, not every time it is accessed.
36 """
37
38 from random import randint, choice
39
40 from threading import Thread
41
42 from time import sleep
43
44 from traits.api import (
45 HasStrictTraits,
46 HasPrivateTraits,
47 Str,
48 Int,
49 Enum,
50 List,
51 Event,
52 Property,
53 cached_property,
54 )
55
56 from traitsui.api import ObjectColumn, Item, TableEditor, View
57
58
59 # -- Person Class ---------------------------------------------------------
60 class Person(HasStrictTraits):
61 """Defines some sample data to display in the TableEditor."""
62
63 name = Str()
64 age = Int()
65 gender = Enum('Male', 'Female')
66
67
68 # -- PropertyListDemo Class -----------------------------------------------
69 class PropertyListDemo(HasPrivateTraits):
70 """Displays a random list of Person objects in a TableEditor that is
71 refreshed every 3 seconds by a background thread.
72 """
73
74 # An event used to trigger a Property value update:
75 ticker = Event()
76
77 # The property being display in the TableEditor:
78 people = Property(List, observe='ticker')
79
80 # Tiny hack to allow starting the background thread easily:
81 begin = Int()
82
83 # -- Traits View Definitions ----------------------------------------------
84
85 traits_view = View(
86 Item(
87 'people',
88 show_label=False,
89 editor=TableEditor(
90 columns=[
91 ObjectColumn(name='name', editable=False, width=0.50),
92 ObjectColumn(name='age', editable=False, width=0.15),
93 ObjectColumn(name='gender', editable=False, width=0.35),
94 ],
95 auto_size=False,
96 show_toolbar=False,
97 sortable=False,
98 ),
99 ),
100 title='Property List Demo',
101 width=0.25,
102 height=0.33,
103 resizable=True,
104 )
105
106 # -- Property Implementations ---------------------------------------------
107 @cached_property
108 def _get_people(self):
109 """Returns the value for the 'people' property."""
110 return [
111 Person(
112 name='%s %s'
113 % (
114 choice(['Tom', 'Dick', 'Harry', 'Alice', 'Lia', 'Vibha']),
115 choice(['Thomas', 'Jones', 'Smith', 'Adams', 'Johnson']),
116 ),
117 age=randint(21, 75),
118 gender=choice(['Male', 'Female']),
119 )
120 for i in range(randint(10, 20))
121 ]
122
123 # -- Default Value Implementations ----------------------------------------
124 def _begin_default(self):
125 """Starts the background thread running."""
126 thread = Thread(target=self._timer)
127 thread.daemon = True
128 thread.start()
129
130 return 0
131
132 # -- Private Methods ------------------------------------------------------
133
134 def _timer(self):
135 """Triggers a property update every 3 seconds for 30 seconds."""
136 for i in range(10):
137 sleep(3)
138 self.ticker = True
139
140
141 # Create the demo:
142 demo = PropertyListDemo()
143 demo.begin
144
145 # Run the demo (if invoked from the command line):
146 if __name__ == '__main__':
147 demo.configure_traits()