Debian Codegraph @

traitsui/examples/demo/Advanced/ListStrAdapter_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 Display an editable List of Strings.
13
14 The ListStrEditor uses a custom ListStrAdapter to define colors and tooltips.
15 """
16
17 from traitsui.list_str_adapter import ListStrAdapter
18 from traits.api import HasTraits, List, Str
19 from traitsui.api import View, Item, ListStrEditor
20
21
22 # -- The adapter ----------------------------------------------------------
23
24 class HeadlinesListAdapter(ListStrAdapter):
25 """ Custom adapter for string lists being edited in the ListStrEditor.
26
27 - Style ALL CAPS titles in red.
28 - Describe the capitalization in the tooltip.
29 """
30
31 def get_text_color(self, object, trait, row):
32 try:
33 row_data = getattr(object, trait)[row]
34 except IndexError:
35 return ""
36
37 if row_data.isupper():
38 return "red"
39 return super().get_text_color(object, trait, row)
40
41 def get_tooltip(self, object, trait, row):
42 try:
43 row_data = getattr(object, trait)[row]
44 except IndexError:
45 # if the ListStr is editable, IndexError indicates the empty next slots
46 return ""
47
48 if row_data.isupper():
49 return "An uppercase headline"
50 elif row_data.istitle():
51 return "A headline in title case"
52 elif row_data.islower():
53 return "A fully lowercase headline"
54 else:
55 return self.tooltip
56
57
58 # -- The class providing the view -------------------------------------
59
60 class HeadlinesListDemo(HasTraits):
61
62 headlines = List(Str)
63
64 view = View(
65 Item(
66 "headlines",
67 show_label=False,
68 editor=ListStrEditor(
69 title="List of headlines (hover for description)",
70 adapter=HeadlinesListAdapter(
71 # the default tooltip for generic rows
72 tooltip="A headline"
73 ),
74 auto_add=True
75 ),
76 # (QT only) the tooltip shown in the area outside of rows
77 # or when the row's tooltip is empty
78 tooltip="List of headlines"
79 ),
80 title='List of headlines',
81 width=320,
82 height=370,
83 resizable=True,
84 )
85
86
87 # -- Set up the Demo ------------------------------------------------------
88
89 demo = HeadlinesListDemo(
90 headlines=[
91 "Shark bites man",
92 "MAN BITES SHARK",
93 "The London Stock Exchange Collapses",
94 "she sells sea shells on the sea shore"
95 ]
96 )
97
98 # Run the demo (in invoked from the command line):
99 if __name__ == "__main__":
100 demo.configure_traits()