Search code examples
gtk3gjs

How can I bind a GtkBox to an array?


I'm making some GTK desktop widgets which monitors stuff like System Tray elements or opened windows for the taskbar.

For the taskbar, an approach I'm taking is re-populate a Gtk.Box each time I get a "change" signal from my window manager: I remove everything from the GtkBox and then I re-add everything based on a query I perform against the window manager after the state change. This way I don't have to worry about ordering or missed signals.

However, I'm wondering if there's a way to make a Gtk.Box bound to an array so that it handles changes by itself. FlowBox has a bind_model method which seems to fit my use case, but FlowBox also seems more complex than a simple Box: doesn't Box (or Container, or Widget) provide a similar mechanism?


Solution

  • GtkBox does not support a feature like this, as it is intended to be a simple container widget.

    Widgets like GtkListBox and GtkFlowBox do by supporting being bound to a GListModel. But neither the widgets nor the list model operate any complex logic; the list model tracks the position and number members, emits an items-changed signal. The GtkListBox and GtkFlowBox track the member widgets, and respond to the signal.

    If you're concerned about performance, you should just implement GListModel for your use case and bind it to a GtkListBox or GtkFlowBox. You can then emit items-changed with the position, removed and added parameters to reflect only the real changes.