menu.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from typing import Any, Callable, Optional
  2. from .. import globals
  3. from ..events import ClickEventArguments, handle_event
  4. from .mixins.text_element import TextElement
  5. from .mixins.value_element import ValueElement
  6. class Menu(ValueElement):
  7. def __init__(self, *, value: bool = False) -> None:
  8. """Menu
  9. Creates a menu.
  10. The menu should be placed inside the element where it should be shown.
  11. :param value: whether the menu is already opened (default: `False`)
  12. """
  13. super().__init__(tag='q-menu', value=value, on_value_change=None)
  14. def open(self) -> None:
  15. """Open the menu."""
  16. self.value = True
  17. def close(self) -> None:
  18. """Close the menu."""
  19. self.value = False
  20. def toggle(self) -> None:
  21. """Toggle the menu."""
  22. self.value = not self.value
  23. class MenuItem(TextElement):
  24. def __init__(self,
  25. text: str = '',
  26. on_click: Optional[Callable[..., Any]] = None, *,
  27. auto_close: bool = True,
  28. ) -> None:
  29. """Menu Item
  30. A menu item to be added to a menu.
  31. :param text: label of the menu item
  32. :param on_click: callback to be executed when selecting the menu item
  33. :param auto_close: whether the menu should be closed after a click event (default: `True`)
  34. """
  35. super().__init__(tag='q-item', text=text)
  36. self.menu = globals.get_slot().parent
  37. self._props['clickable'] = True
  38. def handle_click(_) -> None:
  39. handle_event(on_click, ClickEventArguments(sender=self, client=self.client))
  40. if auto_close:
  41. assert isinstance(self.menu, Menu)
  42. self.menu.close()
  43. self.on('click', handle_click, [])