Skip to content

Commit

Permalink
Merge pull request #2433 from cvwillegen/command-action-property
Browse files Browse the repository at this point in the history
Implement property for Command.action.
  • Loading branch information
freakboy3742 committed Mar 1, 2024
2 parents 83b9d0b + fa177ff commit 84206a9
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/2433.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
An action for a Toga command can now be easily modified after initial construction.
15 changes: 14 additions & 1 deletion core/src/toga/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def __init__(
self.section = section
self.order = order

self.action = wrapped_handler(self, action)
self.action = action

self.factory = get_platform_factory()
self._impl = self.factory.Command(interface=self)
Expand Down Expand Up @@ -244,6 +244,19 @@ def icon(self, icon_or_name: IconContent | None):
else:
self._icon = Icon(icon_or_name)

@property
def action(self) -> ActionHandler | None:
"""The Action attached to the command."""
return self._action

@action.setter
def action(self, action: ActionHandler | None):
"""Set the action attached to the command
Needs to be a valid ActionHandler or ``None``
"""
self._action = wrapped_handler(self, action)

def __lt__(self, other: Any) -> bool:
if not isinstance(other, (Group, Command)):
return False
Expand Down
25 changes: 25 additions & 0 deletions core/tests/command/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,31 @@ def test_create():
)


def test_change_action():
"""A command's action can be changed to another handler"""
action1 = Mock()

cmd = toga.Command(action1, "Test command")

assert cmd.text == "Test command"
assert cmd.shortcut is None
assert cmd.tooltip is None
assert cmd.group == toga.Group.COMMANDS
assert cmd.section == 0
assert cmd.order == 0
assert cmd.action._raw == action1

# Change the action to a something new
action2 = Mock()
cmd.action = action2

assert cmd.action._raw == action2

# Clear the action
cmd.action = None
assert cmd.action._raw is None


def test_create_explicit(app):
"""A command can be created with explicit arguments"""
grp = toga.Group("Test group", order=10)
Expand Down

0 comments on commit 84206a9

Please sign in to comment.