Menu Classes created with Python can be just as dynamic as those created in C++, we'll first start with a base class then add additional features to it
The Base Class
When creating Editor Menu Entries, this is generally what my base class looks like:
@unreal.uclass()
class PythonMenuTool(unreal.ToolMenuEntryScript):
name = "programatic_name"
label = "display Name"
tool_tip = "tool tip!"
def __init__(self, menu, section=""):
"""
given a menu object and a section name,
initialize this python tool and add it to the menu
"""
super().__init__()
if section:
menu.add_section(section, section)
# Initialize the entry data
self.init_entry(
owner_name="custom_owner",
menu=menu.menu_name,
section=section,
name=self.name,
label=self.label,
tool_tip = self.tool_tip
)
# Add this tool to the desired menu
menu.add_menu_entry_object(self)
This class will initialize and add itself to the given menu, it won't do anything yet.
We can use the class like so in our code:
ToolMenus= unreal.ToolMenus.get()
menu = ToolMenus.find_menu("LevelEditor.MainMenu.DemoTools")
PythonMenuTool(menu)
and it will show up in our Demo Tools dropdown menu:
Declaring the Execute
To set what we want out button to do, we can override its execute function:
@unreal.ufunction(override=True)
def execute(self, context):
"""The Python code to execute when pressed"""
print(f"Provided context: {context}")
It will now print a message when pressed
Declaring the Execute Condition
To control whether the menu button can run, we can override its can_execute function:
@unreal.ufunction(override=True)
def can_execute(self, context):
"""Can the user press this menu entry?"""
is_ctrl_down = unreal.InputLibrary.modifier_keys_state_is_control_down(
unreal.InputLibrary.get_modifier_keys_state()
)
return is_ctrl_down
Users must now hold the CTRL key down to use our tool
Dynamic Labels
To set a dynamic label in the menu, we can override its get_label function:
@unreal.ufunction(override=True)
def get_label(self, context):
"""Update the Display Name"""
is_ctrl_down = unreal.InputLibrary.modifier_keys_state_is_control_down(
unreal.InputLibrary.get_modifier_keys_state()
)
return "CTRL is GO!" if is_ctrl_down else "Press CTRL to use"
The Label will now change depending on whether the user is pressing the CTRL key: