Search code examples
rustgtkgtk4

Get children from ListBox (gtk4)


When I was using gtk3 I was able to access a ListBox's children this way:

let list_box = ListBox::new(); 
let label = Label::new(Some("Label 1")); 

list_box.append(&label);

for row in list_box.children() {
    list_box.remove(&row);
}

In gtk4, it seems like children() doesn't exist anymore: "no method named `children` found for struct `gtk4::ListBox`".

I checked ListBox in the gtk4 docs, but I couldn't find anything related to accessing a ListBox's children.

How to access a ListBox's children in gtk4?


Solution

  • There is observe_children, but like it's name suggests you should not modify the container while using it. Or more specifically you can't keep using it's iterator once you modify the underlying container.

    For your usecase you can iterate and remove children using first_child/last_child like this:

    while let Some(row) = list_box.last_child() {
        list_box.remove(&row);
    }