menu_item.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. from typing import Callable, Optional
  2. import justpy as jp
  3. from ..events import ClickEventArguments, handle_event
  4. from ..task_logger import create_task
  5. from .element import Element
  6. class MenuItem(Element):
  7. def __init__(self, text: str = '', on_click: Optional[Callable] = None, *, auto_close: bool = True):
  8. """Menu Item Element
  9. A menu item to be added to a menu.
  10. :param text: label of the menu item
  11. :param on_click: callback to be executed when selecting the menu item
  12. :param auto_close: whether the menu should be closed after a click event (default: `True`)
  13. """
  14. view = jp.QItem(text=text, clickable=True, temp=False)
  15. def handle_click(view, event) -> Optional[bool]:
  16. socket = event.get('websocket')
  17. result = handle_event(on_click, ClickEventArguments(sender=self, socket=socket))
  18. if auto_close:
  19. assert isinstance(self.parent_view, jp.QMenu)
  20. self.parent_view.value = False
  21. create_task(self.parent_view.update())
  22. return result
  23. view.on('click', handle_click)
  24. super().__init__(view)