cgtk4

How to find child widget by name and type on gtk4?


I am trying to find child widgets by name/type from GtkStack. This function is working on gtk3--------

GtkWidget* find_child_by_name (GtkWidget* parent, const gchar* name)
{
  printf("GtkWidget Name: %s\n\n", gtk_widget_get_name (parent));

    if (g_strcmp0(gtk_widget_get_name(parent), name) == 0)
        return parent;

    GList* children = NULL;
    if (GTK_IS_CONTAINER(parent))
        children = gtk_container_get_children(GTK_CONTAINER(parent));

    while (children != NULL)
    {
        GtkWidget* widget = find_child_by_name(children->data, name);

        if (widget != NULL)
            return widget;

        children = children->next;
    }
    return NULL;
}

But gtk_container_get_children function has been removed in Gtk4. I saw this function gtk_widget_observe_children, but I don't understand how it works. How can this be done in the case of Gtk4?


Solution

  • In GTK4, there are two features here that you can use well for it:

    GtkWidget*
    gtk_widget_get_first_child (
      GtkWidget* widget
    )
    

    and

    GtkWidget*
    gtk_widget_get_next_sibling (
      GtkWidget* widget
    )
    

    With a for - loop you can then go through all children.

    A meaningful application could then look something like this:

    for (child = gtk_widget_get_first_child (widget);
                child != NULL;
                child = gtk_widget_get_next_sibling(child))
        {
            /* your code */
        }
    

    The sake of completeness should be mentioned, that the following function also gives:

    GtkWidget*
    gtk_widget_get_prev_sibling (
      GtkWidget* widget
    )
    

    The e.g. can be used in combination with the following function:

    GtkWidget*
    gtk_widget_get_last_child (
      GtkWidget* widget
    )
    

    Greetings