The way to get all children or children count of widget in GTK4

Hey guys,

Is there a way to get all children or children count of widget lightly in GTK4?

In GTK3, there are get_children and foreach methods to done that,
in GTK4, I found methods like get_first_child/get_last_child/get_next_sibling/get_prev_sibling to support this.

“Lightly”?

The get_first_child()/get_next_sibling() API is for widget implementations; it will iterate over every child of a widget. Let’s say, for instance, that you have a custom “box with an arrow” widget:

+-----+-----------------------+
|  V  |                       |
+-----+-----------------------+

And you can only add children to the right of the arrow. You’re probably interested in the number of children you added, not in the arrow itself. In that case, the “box with an arrow” widget should have a get_n_children() method. If you use get_first_child()/get_next_sibling() to iterate the children of a widget, you’ll get the arrow and the rest of the children. This is just the simplest case; there are widget with nested children, and one of those nested children might be where you add your own widgets. In that case, iterating won’t give you the number of children you added—unless you know exactly how the widget is constructed.

For all intents and purposes, you should count the children you’re adding yourself in your own code; this is usually easier, and will yield the appropriate result. Alternatively, you should write your own widget that counts its children and that you can query.

1 Like

Just focus on non-internal children directly only:

get_n_children could solve one of problems,

for compatibility with GTK3, we should consider to provide method like: get_children.
and I hope there is way to iterate all children with foreach statement:

var children = box.get_children();
foreach(var widget in children) {
      // do something 
}

So, pls considering add two methods:
get_n_children()
get_children()

We are not going to add a generic API for that.

As I said in my first reply: widgets may have internal children. Some widgets only have internal children. This means each widget has to provide a way to get the list of children, if it allows adding them.

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