SimpleAction variant vs state for menu models

I want to pass some argument to the action that integrated with menu.

Seems that stateful actions is only one option for SimpleAction usage with menu model?

Because I get error on menu item activate without value.

Asking, because wrote lot of code for state implementation, where just to call my action with values once:

  1. save current state to memory
  2. change state
  3. apply action
  4. return state from #1 values

With variant, I can just only call the action once without manual state management (e.g. returning it back all the time)

Hi,

Is the value always the same for a given menu item?
If yes, a normal non-stateful SimpleAction will do the trick.

Stateful actions is intended for cases where activate signal is not enough but you also want to track changes of a value (i.e. the action “state”).
In menus, it’s typically a checkbox, which can be shown checked/unchecked, depending on the action’s state.

1 Like

Hi, thanks for reply

No, the value is different,
in fact, that’s “Append new tab” action for browser app

It used in global menu (with default values tuple) but also could be activated somewhere from content controller (e.g. on middle click on link, or as the additional context menu for tab, where new tab position depends of current position (stored in state))

I want to apply it values once, so can just use Variant, not state, but with Variant it does not work in global menu, because it model does not implement Variant but State only.

So I manage it state manually - set and reset every time

This is what I would do (Python code):

def on_newtab(action, param):
    if param is not None:
        url = param.unpack()
        open_tab(url)

# Create simple action, with string parameter
action = Gio.SimpleAction.new('newtab', GLib.VariantType('s'))
action.connect('activate', on_newtab)

# Add menu item, with "about:blank" as URL
menu.append(_("New Tab"), "notebook.newtab('about:blank')")

This way, you can either activate the action manually with
widget.activate_action('mygroup.newtab', "https://gnome.org/")
or with the menu item, using the default “about:blank” URL.

1 Like

hm, never supposed I would call the methods by string (my thoughts like object-oriented robot) but thanks anyway for idea!

It’s not “a method”: it’s an action with a parameter: Actions - GNOME Developer Documentation

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.