Debian Codegraph @

traitsui/examples/demo/Extras/Tree_editor_with_TreeNodeRenderer.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 illustrates use of TreeNodeRenderers for displaying more complex
13 contents inside the cells of a TreeEditor.
14
15 To run this demonstration successfully, you must have **NumPy**
16 (``numpy``) installed.
17 """
18
19 from random import choice, uniform
20 import colorsys
21
22 import numpy as np
23
24 from pyface.qt import QtCore, QtGui, qt_api
25 from traits.api import Array, Float, HasTraits, Instance, Int, List, Str
26
27 from traitsui.api import TreeEditor, TreeNode, UItem, View, RGBColor
28 from traitsui.tree_node_renderer import AbstractTreeNodeRenderer
29 from traitsui.qt.tree_editor import WordWrapRenderer
30
31
32 class MyDataElement(HasTraits):
33 """A node in a tree of data."""
34
35 #: Some text to display.
36 text = Str()
37
38 #: A random walk to plot.
39 data = Array
40
41 #: A color to show as an icon.
42 color = RGBColor
43
44 def _data_default(self):
45 return np.random.standard_normal((1000,)).cumsum()
46
47 def _color_default(self):
48 return colorsys.hsv_to_rgb(uniform(0.0, 1.0), 1.0, 1.0)
49
50
51 class MyData(HasTraits):
52 """The root node for a tree of data."""
53
54 #: The name of the root node.
55 name = Str('Rooty McRootface')
56
57 #: The elements contained in the root node.
58 elements = List(Instance(MyDataElement))
59
60 def _elements_default(self):
61 DATA_ELEMENTS = (
62 'I live on\nmultiple\nlines!',
63 'Foo\nBar',
64 'Baz',
65 'Qux',
66 'z ' * 20,
67 __doc__,
68 )
69 return [MyDataElement(text=choice(DATA_ELEMENTS)) for _ in range(5)]
70
71
72 class SparklineRenderer(AbstractTreeNodeRenderer):
73 """Renderer that draws sparklines into a cell."""
74
75 #: This renderer handles all rendering.
76 handles_all = True
77
78 #: This renderer handles text rendering (there is none).
79 handles_text = True
80
81 #: The scale for y-values.
82 y_scale = Float(1.0)
83
84 #: The extra border applied by Qt internally
85 # XXX get this dynamically from Qt? How?
86 extra_space = Int(8)
87
88 def paint(self, editor, node, column, object, paint_context):
89 painter, option, index = paint_context
90 data = self.get_data(object)
91
92 xs = (
93 np.linspace(0, option.rect.width(), len(data)) + option.rect.left()
94 )
95 ys = (data.max() - data) / self.y_scale + option.rect.top()
96
97 height = option.rect.height()
98 plot_height = ys.ptp()
99 extra = height - plot_height
100 if bool(option.displayAlignment & QtCore.Qt.AlignmentFlag.AlignVCenter):
101 ys += extra / 2
102 elif bool(option.displayAlignment & QtCore.Qt.Bottom):
103 ys += extra
104
105 if bool(option.state & QtGui.QStyle.StateFlag.State_Selected):
106 painter.fillRect(option.rect, option.palette.highlight())
107
108 points = [QtCore.QPointF(x, y) for x, y in zip(xs, ys)]
109 old_pen = painter.pen()
110 if bool(option.state & QtGui.QStyle.StateFlag.State_Selected):
111 painter.setPen(QtGui.QPen(option.palette.highlightedText(), 0))
112 try:
113 if qt_api.startswith('pyside'):
114 painter.drawPolyline(points)
115 else:
116 painter.drawPolyline(*points)
117 finally:
118 painter.setPen(old_pen)
119
120 return None
121
122 def get_data(self, object):
123 return object.data
124
125 def size(self, editor, node, column, object, size_context):
126 data = self.get_data(object)
127 return (100, data.ptp() / self.y_scale + self.extra_space)
128
129
130 class SparklineTreeNode(TreeNode):
131 """A TreeNode that renders sparklines in column index 1"""
132
133 #: static instance of SparklineRenderer
134 #: (it has no state, so this is fine)
135 sparkline_renderer = SparklineRenderer()
136
137 #: static instance of WordWrapRenderer
138 #: (it has no state, so this is fine)
139 word_wrap_renderer = WordWrapRenderer()
140
141 def get_renderer(self, object, column=0):
142 if column == 1:
143 return self.sparkline_renderer
144 else:
145 return self.word_wrap_renderer
146
147 def get_icon(self, object, is_expanded):
148 return object.color
149
150
151 class SparklineTreeView(HasTraits):
152 """Class that views the data with sparklines."""
153
154 #: The root of the tree.
155 root = Instance(MyData, args=())
156
157 traits_view = View(
158 UItem(
159 'root',
160 editor=TreeEditor(
161 nodes=[
162 TreeNode(
163 node_for=[MyData],
164 children='elements',
165 label='name',
166 ),
167 SparklineTreeNode(
168 node_for=[MyDataElement],
169 auto_open=True,
170 label='text',
171 ),
172 ],
173 column_headers=["The Tree View", "The Sparklines"],
174 hide_root=False,
175 editable=False,
176 ),
177 ),
178 resizable=True,
179 width=400,
180 height=300,
181 )
182
183
184 if __name__ == '__main__':
185 SparklineTreeView().configure_traits()