color_input.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from typing import Any, Callable, Optional
  2. from .button import Button as button
  3. from .color_picker import ColorPicker as color_picker
  4. from .mixins.disableable_element import DisableableElement
  5. from .mixins.value_element import ValueElement
  6. class ColorInput(ValueElement, DisableableElement):
  7. LOOPBACK = False
  8. def __init__(self,
  9. label: Optional[str] = None, *,
  10. placeholder: Optional[str] = None,
  11. value: str = '',
  12. on_change: Optional[Callable[..., Any]] = None,
  13. preview: bool = False,
  14. ) -> None:
  15. """Color Input
  16. This element extends Quasar's `QInput <https://quasar.dev/vue-components/input>`_ component with a color picker.
  17. :param label: displayed label for the color input
  18. :param placeholder: text to show if no color is selected
  19. :param value: the current color value
  20. :param on_change: callback to execute when the value changes
  21. :param preview: change button background to selected color (default: False)
  22. """
  23. super().__init__(tag='q-input', value=value, on_value_change=on_change)
  24. if label is not None:
  25. self._props['label'] = label
  26. if placeholder is not None:
  27. self._props['placeholder'] = placeholder
  28. with self.add_slot('append'):
  29. self.picker = color_picker(on_pick=lambda e: self.set_value(e.color))
  30. self.button = button(on_click=self.open_picker, icon='colorize') \
  31. .props('flat round', remove='color').classes('cursor-pointer')
  32. self.preview = preview
  33. self._update_preview()
  34. def open_picker(self) -> None:
  35. """Open the color picker"""
  36. if self.value:
  37. self.picker.set_color(self.value)
  38. self.picker.open()
  39. def _handle_value_change(self, value: Any) -> None:
  40. super()._handle_value_change(value)
  41. self._update_preview()
  42. def _update_preview(self) -> None:
  43. if not self.preview:
  44. return
  45. self.button.style(f'''
  46. background-color: {(self.value or "#fff").split(";", 1)[0]};
  47. text-shadow: 2px 0 #fff, -2px 0 #fff, 0 2px #fff, 0 -2px #fff, 1px 1px #fff, -1px -1px #fff, 1px -1px #fff, -1px 1px #fff;
  48. ''')