Created
September 14, 2021 15:18
-
-
Save danieljfarrell/75294c9601fb2f336dc97d39394c40f7 to your computer and use it in GitHub Desktop.
TraitsUI tree editor example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from traits.api import HasTraits, Str, List, Button, Any | |
from traitsui.api import TreeNode, TreeEditor, View, ModelView, Group, VGroup, Item | |
from pkg_resources import resource_filename | |
tree_icon_path = resource_filename("traitsui", "wx/images") | |
class Measurement(HasTraits): | |
name = Str("Measurement") | |
class Document(HasTraits): | |
measurements = List(Measurement) | |
class MyTreeNode(TreeNode): | |
icon_path = tree_icon_path | |
icon_group = "group" | |
icon_item = "item" | |
icon_open = "open" | |
def can_rename_me(self, obj): | |
return False | |
class MeasurementNode(MyTreeNode): | |
pass | |
class CustomTreeEditor(TreeEditor): | |
no_view = View() | |
document_tree_editor = CustomTreeEditor( | |
nodes=[ | |
MyTreeNode( | |
node_for=[Document], | |
auto_open=True, | |
children="measurements", | |
label="=Measurements", | |
view=View(), | |
), | |
MyTreeNode(node_for=[Measurement], auto_open=True, children="", label="name",), | |
], | |
editable=True, | |
hide_root=True, | |
orientation="vertical", | |
selected="selected", | |
selection_mode="single", | |
) | |
class DocumentView(ModelView): | |
model = Document | |
selected = Any | |
add_btn = Button("Add Measurement") | |
def _add_btn_fired(self): | |
self.model.measurements.append( | |
Measurement(name=str(len(self.model.measurements))) | |
) | |
self.selected = self.model.measurements[-1] | |
def default_traits_view(self): | |
return View( | |
Group( | |
Item("add_btn", show_label=False), | |
VGroup( | |
Item( | |
name="model", | |
editor=document_tree_editor, | |
resizable=True, | |
show_label=False, | |
width=1.0, | |
), | |
), | |
), | |
dock="vertical", | |
resizable=True, | |
title="Document", | |
) | |
if __name__ == "__main__": | |
document = Document(measurements=[Measurement(name=str(x)) for x in range(50)]) | |
document_view = DocumentView(model=document) | |
document_view.configure_traits() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment