Get parent object

In GTK4, is there a simple way to get the object of an object’s parent, rather than just Gtk.Widget?
class MyButton is in class MyBox,
MyBox has a public int parameter called ‘selection’,
I’d lilke to set ‘selection’ from code within MyButton, as cleanly as possible.
Currently the following works:

MyBox mybox = (MyBox) this.get_ancestor(typeof(MyBox));
mybox.selection = 1;

however this feels like the wrong way to do it, especially if we don’t know the typeof a parent, and given that the parent’s ‘selection’ parameter is public anyway.

An alternative would be to use GAction: Gtk – 4.0: Overview of actions in GTK

You can create a GSimpleActionGroup and insert it into MyBox using Gtk.Widget.insert_action_group() with prefix mybox. In that group, add a stateful action whose state is the selection.

Then your button can simply have action-name set to and action-target set to 1, and it will find the action in the widget’s ancestors and activate it on click.

If appropriate, you can also add the action directly to the GtkApplicationWindow where it would have a win prefix. Obviously if your window has more than one MyBox widget, you wouldn’t want to do that.

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