Debian Codegraph @

traitsui/examples/demo/Dynamic_Forms/dynamic_form_using_instances.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 Dynamic restructuring a user interface using Instance editor and Handler
13
14 How to dynamically change the *structure* of a user interface (not merely which
15 components are visible), depending on the value of another trait.
16
17 This code sample shows a simple implementation of the dynamic
18 restructuring of a View on the basis of some trait attribute's
19 assigned value.
20
21 The demo class "Person" has attributes that apply to all instances
22 ('first_name', 'last_name', 'age') and a single attribute 'misc'
23 referring to another object whose traits are specific to age
24 group (AdultSpec for adults 18 and over, ChildSpec for children
25 under 18). The 'misc' attribute is re-assigned to a new instance
26 of the appropriate type when a change to 'age' crosses the range
27 boundary.
28
29 The multi-attribute instance assigned to 'misc' is edited by means
30 of a single InstanceEditor, which is displayed in the 'custom' style
31 so that the dynamic portion of the interface is displayed in a panel
32 rather than a separate window.
33
34 It is necessary to use a Handler because otherwise when the instance is
35 updated dynamically, Traits UI will not detect the change and the UI will not
36 be reconfigured. This is due to architectural limitations of the current
37 version of Traits UI.
38
39 Compare this to the simpler, but less powerful demo of *enabled_when*.
40 """
41
42 from traits.api import HasTraits, Str, Range, Enum, Bool, Instance
43
44 from traitsui.api import Item, Group, View, Handler, Label
45
46
47 class Spec(HasTraits):
48 """An empty class from which all age-specific trait list classes are
49 derived.
50 """
51
52 pass
53
54
55 class ChildSpec(Spec):
56 """Trait list for children (assigned to 'misc' for a Person when age < 18)."""
57
58 legal_guardian = Str()
59 school = Str()
60 grade = Range(1, 12)
61
62 traits_view = View('legal_guardian', 'school', 'grade')
63
64
65 class AdultSpec(Spec):
66 """Trait list for adults (assigned to 'misc' for a Person when age >= 18)."""
67
68 marital_status = Enum('single', 'married', 'divorced', 'widowed')
69 registered_voter = Bool()
70 military_service = Bool()
71
72 traits_view = View(
73 'marital_status', 'registered_voter', 'military_service'
74 )
75
76
77 class PersonHandler(Handler):
78 """Handler class to perform restructuring action when conditions are met.
79 The restructuring consists of replacing a ChildSpec instance by an
80 AdultSpec instance, or vice-versa. We would not need a handler to listen
81 for a change in age, but we do need a Handler so that Traits UI will
82 respond immediately to changes in the viewed Person, which require
83 immediate restructuring of the UI.
84 """
85
86 def object_age_changed(self, info):
87 if (info.object.age >= 18) and (
88 not isinstance(info.object.misc, AdultSpec)
89 ):
90 info.object.misc = AdultSpec()
91 elif (info.object.age < 18) and (
92 not isinstance(info.object.misc, ChildSpec)
93 ):
94 info.object.misc = ChildSpec()
95
96
97 class Person(HasTraits):
98 """Demo class for demonstrating dynamic interface restructuring."""
99
100 first_name = Str()
101 last_name = Str()
102 age = Range(0, 120)
103 misc = Instance(Spec)
104
105 # Interface for attributes that are always visible in interface:
106 gen_group = Group(
107 Item(name='first_name'),
108 Item(name='last_name'),
109 Item(name='age'),
110 label='General Info',
111 show_border=True,
112 )
113
114 # Interface for attributes that depend on the value of 'age':
115 spec_group = Group(
116 Group(Item(name='misc', style='custom'), show_labels=False),
117 label='Additional Info',
118 show_border=True,
119 )
120
121 # A simple View is enough as long as the right handler is specified:
122 view = View(
123 Group(
124 gen_group,
125 '10',
126 Label("Using Instances and a Handler:"),
127 '10',
128 spec_group,
129 ),
130 title='Personal Information',
131 buttons=['OK'],
132 resizable=True,
133 width=300,
134 handler=PersonHandler(),
135 )
136
137
138 # Create the demo:
139 demo = Person(
140 first_name="Samuel", last_name="Johnson", age=18, misc=AdultSpec()
141 )
142
143 # Run the demo (if invoked from the command line):
144 if __name__ == '__main__':
145 demo.configure_traits()