classes/class_popupmenu #209
Replies: 1 comment 1 reply
-
|
A handy way to reference PopupMenu items is using an enum. For example: enum {
CHECKBOX_ONE,
CHECKBOX_TWO,
}
var menu: PopupMenu
func _ready() -> void:
# Create popup menu
menu = PopupMenu.new()
menu.add_check_item("Checkbox 1", CHECKBOX_ONE)
menu.add_separator() # Uh oh! This will cause a problem! See below.
menu.add_check_item("Checkbox 2", CHECKBOX_TWO)
# Add signal handler
menu.id_pressed.connect(_on_popup_item_pressed)
func _on_popup_item_pressed(id: int) -> void:
# Update item checked state
var item_idx = menu.get_item_index(id)
var item_was_checked = menu.get_item_checked(item_idx)
menu.set_item_checked(idx, not item_was_checked)
# Run the signal handler for this item
match id:
CHECKBOX_ONE:
_on_checkbox_one_changed(not item_was_checked)
CHECKBOX_TWO:
_on_checkbox_two_changed(not item_was_checked)
func _on_checkbox_one_checked(checked: bool) -> void:
pass
func _on_checkbox_two_checked(checked: bool) -> void:
pass
If you need to reference PopupMenu items using their ID, make sure you assign an ID to each item, even separators! If you don't, the ID will be set as the length of the menu ( If we run: for idx in popup.item_count:
prints(
"idx", idx,
"id", popup.get_item_id(idx),
"text", popup.get_item_text(idx)
)we will get the output: You can see that there are two items with an id of 1. When You can solve this problem however you want, but here's a suggestion: since multiple items can have the same ID, why not max out the id value? The intro says Our re-written func _ready() -> void:
# Create popup menu
menu = PopupMenu.new()
menu.add_check_item("Checkbox 1", CHECKBOX_ONE)
menu.add_separator("", 2147483647) # ahh that's better!
menu.add_check_item("Checkbox 2", CHECKBOX_TWO)
# Add signal handler
menu.id_pressed.connect(_on_popup_item_pressed)You could also set the ID to a lower number you know you won't use, like |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
classes/class_popupmenu
Inherits: Popup< Window< Viewport< Node< Object A modal window used to display a list of options. Description: PopupMenu is a modal window used to display a list of options. Useful for toolbars and...
https://docs.godotengine.org/en/stable/classes/class_popupmenu.html
Beta Was this translation helpful? Give feedback.
All reactions