How to remove all children widgets from Box in Rust?

I want to update entire GTK box with new widgets in runtime

this code does not work, but maybe describes what do I mean:

// Cleanup
for child in widget.observe_children() {
    self.widget.remove(&child);
}

// widget.append(new_widget)

That is horrific, please never call observe_children(). The documentation should already make it clear.

Remove the box, and construct a new box. That will take care of all the children.

If you find yourself doing this too many times to represent different (well known) states, then I strongly recommend using a GtkStack and have different pages for each state.

1 Like

Thanks for reply, at this point I can’t remove the Box as used by parents.

I want to keep this Box as container for different mime types given by the runtime: text labels, image view, media stream, etc.

Found solution like that, is it still horrible or memory unsafe?

// cleanup
while let Some(child) = widget.last_child() {
    widget.remove(&child)
}

// widget.append(video | picture | label | etc)

That makes zero sense: if you have the parent, then you can remove the box.

You should have a stack with a page for each different MIME type you want to display, and update the widgets inside the appropriate page with the data you want to display. Removing the widgets and adding them back is just going to cause a bunch of CSS and state invalidations for no reason.

A basic example of the structure:

stack
+---- page: video
      +---- video
      +---- playback controls
      +---- metadata
+---- page: picture
      +---- image
      +---- metadata
+---- page: text
      +---- metadata
+---- page: audio
      +---- playback controls
      +---- metadata

It’s less horrible than creating a ListModel with all the children just because you want to use an iterator; it’s still horrible because that API should only be used when implementing your own container widget, just like set_parent() and unparent() are not for adding and removing widgets.

1 Like