option_menu.gd 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. class_name OptionMenu
  2. extends MenuButton
  3. signal option_selected(item_path)
  4. signal option_changed(item_path, checked)
  5. func add_menu_item(item_path, checkbox = false, checked = false):
  6. var path_elements = item_path.split("/", false)
  7. var path_element_count = path_elements.size()
  8. assert(path_element_count > 0)
  9. var path = ""
  10. var popup = get_popup()
  11. for element_index in range(path_element_count - 1):
  12. var popup_label = path_elements[element_index]
  13. path += popup_label + "/"
  14. popup = _add_popup(popup, path, popup_label)
  15. var label = path_elements[path_element_count - 1]
  16. if checkbox:
  17. popup.add_check_item(label)
  18. popup.set_item_checked(popup.get_item_count() - 1, checked)
  19. else:
  20. popup.add_item(label)
  21. func _add_item(parent_popup, label):
  22. parent_popup.add_item(label)
  23. func _add_popup(parent_popup, path, label):
  24. if parent_popup.has_node(label):
  25. var popup_node = parent_popup.get_node(label)
  26. var popup_menu = popup_node as PopupMenu
  27. assert(popup_menu)
  28. return popup_menu
  29. var popup_menu = PopupMenu.new()
  30. popup_menu.name = label
  31. popup_menu.hide_on_checkable_item_selection = false
  32. parent_popup.add_child(popup_menu)
  33. parent_popup.add_submenu_item(label, label)
  34. popup_menu.index_pressed.connect(_on_item_pressed.bind(popup_menu, path))
  35. return popup_menu
  36. func _on_item_pressed(item_index, popup_menu, path):
  37. var item_path = path + popup_menu.get_item_text(item_index)
  38. if popup_menu.is_item_checkable(item_index):
  39. var checked = not popup_menu.is_item_checked(item_index)
  40. popup_menu.set_item_checked(item_index, checked)
  41. emit_signal("option_changed", item_path, checked)
  42. else:
  43. emit_signal("option_selected", item_path)