You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.9 KiB

  1. from contextlib import contextmanager
  2. from gooey.gui.components.widgets.bases import TextContainer
  3. import wx
  4. from gooey.gui import formatters
  5. from gooey.gui.lang.i18n import _
  6. class Dropdown(TextContainer):
  7. def getWidget(self, parent, *args, **options):
  8. default = _('select_option')
  9. return wx.ComboBox(
  10. parent=parent,
  11. id=-1,
  12. # str conversion allows using stringyfiable values in addition to pure strings
  13. value=str(default),
  14. choices=[str(default)] + [str(choice) for choice in self._meta['choices']],
  15. style=wx.CB_DROPDOWN)
  16. def setOptions(self, options):
  17. with self.retainSelection():
  18. self.widget.Clear()
  19. self.widget.SetItems([_('select_option')] + options)
  20. def setValue(self, value):
  21. ## +1 to offset the default placeholder value
  22. index = self._meta['choices'].index(value) + 1
  23. self.widget.SetSelection(index)
  24. def getWidgetValue(self):
  25. value = self.widget.GetValue()
  26. # filter out the extra default option that's
  27. # appended during creation
  28. if value == _('select_option'):
  29. return None
  30. return value
  31. def formatOutput(self, metadata, value):
  32. return formatters.dropdown(metadata, value)
  33. @contextmanager
  34. def retainSelection(self):
  35. """"
  36. Retains the selected dropdown option (when possible)
  37. across mutations due to dynamic updates.
  38. """
  39. prevSelection = self.widget.GetSelection()
  40. prevValue = self.widget.GetValue()
  41. try:
  42. yield
  43. finally:
  44. current_at_index = self.widget.GetString(prevSelection)
  45. if prevValue == current_at_index:
  46. self.widget.SetSelection(prevSelection)
  47. else:
  48. self.widget.SetSelection(0)