GTK4 actions not active unless in app or window

I’m trying to get some actions to be selectable from an options menu in GTK4. The actions should be connected to a project view widget that exists in a stack where only one project view is visible at a time. I think I figured out how this is supposed to be done - by making an action group and place it in the project view widget. Then connect this from the menu using action name and namespace. However, I can’t seem to get it to work. I have a couple of actions for the window and those work fine.

I do this in the project view widget to make a named group and attach a number of actions.

const GActionEntry project_entries[] =
{
	{"undo", undo_activated, NULL, NULL, NULL},
	{"redo", redo_activated, NULL, NULL, NULL},
};

GSimpleActionGroup *action_group = g_simple_action_group_new();
g_action_map_add_action_entries(G_ACTION_MAP(action_group), project_entries, G_N_ELEMENTS(project_entries), view);
gtk_widget_insert_action_group(GTK_WIDGET(view), "project", G_ACTION_GROUP(action_group));

In my menu I attempt to connect the entries to the corresponding group and action.

<section>
	<item>
		<attribute name="label" translatable="yes">_Undo</attribute>
		<attribute name="action">project.undo</attribute>
	</item>
</section>

The result is a greyed out entry in the menu. I’m not sure how to figure out what’s wrong. There’s nothing printed to standard out during the application lifetime. Is there something I have to do to ensure that the actions are found in the widget hierarchy?

Hi,

To which widget is that menu attached?

For actions to be detected, they must be run from a child of the widget holding the action group, or from that widget itself.
See description of Gtk.Widget.activate_action

So if you use a context menu in that project view, the action will be found, but if the menu is attached to the window then that won’t work.
(for example, in case you have several project views in the window, then the window menu won’t be able to guess for which project view to activate that action…)

The window is parent of all widgets, so inserting the action to the window’s group allows it to always be found.

1 Like

Thank you very much for the enlightening answer!

My menu is attached to the window so that explains why the project view actions couldn’t be found. I thought GTK would search through the widget tree for the action amongst the visible ones. I’ll split the menu into two to solve it.

1 Like

You may also create dispatcher action like win.undo, attached to the window, and in its handler lookup for the visible projectview and call activate_action("project.undo") on it.

1 Like

That’s a good idea! Thanks!

1 Like

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