tree.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from typing import Any, Callable, List, Optional
  2. from ..element import Element
  3. from ..events import GenericEventArguments, ValueChangeEventArguments, handle_event
  4. class Tree(Element):
  5. def __init__(self, nodes: List, *,
  6. node_key: str = 'id',
  7. label_key: str = 'label',
  8. children_key: str = 'children',
  9. on_select: Optional[Callable[..., Any]] = None,
  10. on_expand: Optional[Callable[..., Any]] = None,
  11. on_tick: Optional[Callable[..., Any]] = None,
  12. ) -> None:
  13. """Tree
  14. Display hierarchical data using Quasar's `QTree <https://quasar.dev/vue-components/tree>`_ component.
  15. If using IDs, make sure they are unique within the whole tree.
  16. :param nodes: hierarchical list of node objects
  17. :param node_key: property name of each node object that holds its unique id (default: "id")
  18. :param label_key: property name of each node object that holds its label (default: "label")
  19. :param children_key: property name of each node object that holds its list of children (default: "children")
  20. :param on_select: callback which is invoked when the node selection changes
  21. :param on_expand: callback which is invoked when the node expansion changes
  22. :param on_tick: callback which is invoked when a node is ticked or unticked
  23. """
  24. super().__init__('q-tree')
  25. self._props['nodes'] = nodes
  26. self._props['node-key'] = node_key
  27. self._props['label-key'] = label_key
  28. self._props['children-key'] = children_key
  29. self._props['selected'] = []
  30. self._props['expanded'] = []
  31. self._props['ticked'] = []
  32. def update_prop(name: str, value: Any) -> None:
  33. if self._props[name] != value:
  34. self._props[name] = value
  35. self.update()
  36. def handle_selected(e: GenericEventArguments) -> None:
  37. update_prop('selected', e.args)
  38. handle_event(on_select, ValueChangeEventArguments(sender=self, client=self.client, value=e.args))
  39. self.on('update:selected', handle_selected)
  40. def handle_expanded(e: GenericEventArguments) -> None:
  41. update_prop('expanded', e.args)
  42. handle_event(on_expand, ValueChangeEventArguments(sender=self, client=self.client, value=e.args))
  43. self.on('update:expanded', handle_expanded)
  44. def handle_ticked(e: GenericEventArguments) -> None:
  45. update_prop('ticked', e.args)
  46. handle_event(on_tick, ValueChangeEventArguments(sender=self, client=self.client, value=e.args))
  47. self.on('update:ticked', handle_ticked)