This is the ninth entry in A Field Guide to GTK Widgets, a series about which widget to reach for, when, and what bites you when you do. The previous post built a sortable table. This one gives it folders. The complete, runnable code lives in the companion repo.


Where we left off

The photo library from the last post was flat: twelve photos, one row each, all at the same level. Real libraries aren’t. Mine is years, then trips inside the years, then photos inside the trips, and sometimes a stray photo sitting loose in a year folder because I never got round to filing it.

Search for “GTK tree view” and nearly everything you find is about GtkTreeView with a GtkTreeStore behind it. Both have been deprecated since GTK 4.10, and the answers still compile, which is how they keep getting copied. The replacement is three pieces: TreeListModel, TreeListRow and TreeExpander. None of them is a new kind of view. The tree goes into the model, and the ListView and ColumnView from earlier posts display it as rows.

The example is the same library as a tree. Three years, five trips, an empty Inbox folder and fifteen photos. It’s shown as a ColumnView with an expander in the Name column and as a ListView outline, in an AdwViewStack, both on one MultiSelection.


A tree is a list that knows about depth

A TreeListModel is a list model. It wraps a root model, here a GListStore of the three year folders, and reports one item per visible row. Expand 2025 and its two trips and its loose photo are spliced into the list straight after it, so the model grows by three and every row below moves down. Collapse it and they’re removed again.

Every model above it sees an ordinary list getting insertions and removals, so the sort model, the selection and both views are the same classes as in every earlier post. Nearly all the hierarchy lives in this one layer, and the one exception is the sorter, which gets its own section below.

The tree model finds out what’s under an item by asking you, through a closure you pass at construction:

let tree = gtk::TreeListModel::new(root.clone(), false, false, |item| {
    let node = item.downcast_ref::<Node>().unwrap();
    println!("children of {}?", node.name());
    node.children().map(|children| children.upcast())
});

Return a list model and the item is a folder that can be expanded. Return None and it’s a leaf. Node is a GObject that’s either a folder or a photo, and a folder owns a GListStore of its own children, which is what that call hands back.

The first false is passthrough and the second is autoexpand. I’ll come back to both.


The closure gets called a lot

The println! is there to show when the closure runs. Before I’d clicked anything, the log had six lines:

children of 2026?
children of 2025?
children of 2024?
children of 2024?
children of 2025?
children of 2026?

Three rows on screen, none of them expanded, each asked twice. The expander draws an arrow only on rows that can expand, and the row finds that out by calling your closure and throwing the model away. Expanding 2025 called it again for 2025 and then for each of its children, which needed arrows of their own.

The other surprise was what collapse does. Collapsing a row drops the child model the closure gave it, and expanding again calls the closure for a fresh one. So the closure isn’t a one-time setup step. It runs whenever GTK wants to know, and it has to be cheap and give the same answer every time.

That decides where the children live. If the closure built a new store each time from some other source, anything changed while the folder was closed would have to be rebuilt correctly on the next call. In the example the folder keeps its store, and the closure returns that same object:

pub fn children(&self) -> Option<gio::ListStore> {
    self.imp().children.borrow().clone()
}

The tree model only borrows it while the row is open. A photo added to a closed folder goes into the store, and it’s there when the folder opens.

Two smaller points from the TreeListModel docs are worth keeping in mind. None is permanent: the row it was returned for is a leaf for good and never gets an arrow, so a folder that might get children later has to return a model, even an empty one. That’s why the empty Inbox still gets an arrow and opens to nothing. And every Node keeps its parent as a weak reference, because a folder holding its children and each child holding its folder strongly would be a cycle that never frees.


The expander needs the row

With passthrough off, which is what you want, the items the tree model hands out aren’t Nodes. Each is a TreeListRow, a small object that wraps the Node and adds what only the tree knows: depth, whether it’s expanded, whether it can be, and its parent row. Every factory and sorter above the tree model gets these rows.

The expander needs the row. It reads the depth to indent, and the expanded state to draw the arrow and toggle it on a click. So the Name column’s factory binds the cell’s item to the expander’s list-row property, and reaches the Node one hop further, through the row’s own item:

let expander = gtk::TreeExpander::builder().child(&content).build();
cell.set_child(Some(&expander));

gtk::ColumnViewCell::this_expression("item").bind(&expander, "list-row", Some(cell));

let node = gtk::ColumnViewCell::this_expression("item")
    .chain_property::<gtk::TreeListRow>("item");
node.chain_property::<Node>("name")
    .bind(&label, "label", Some(cell));

The expander wraps the icon and label and handles the indent and arrow itself. Binding item to list-row is what GTK’s own demos do, and because it’s an expression binding it clears on unbind without any code from me.

Only Name gets an expander. Kind and Size are ordinary label cells, so their text sits at the column’s left or right edge whatever the depth, and the indentation only shows in the first column, the way a file manager’s list view lays it out.

With passthrough on, the tree model hands out the Nodes themselves, and you get a TreeListRow when you need one by asking the model for row(position). It saves a hop in the factories. It also rules out the tree-aware sorter in the next section, so the example leaves it off.

The outline view is the same factory written against a ListItem instead of a ColumnViewCell: an expander per row, with the name and the folder total inside it.


Sorting a tree

The column sorters are exactly the ones from the last post, a StringSorter on name and a NumericSorter on size, comparing Nodes. They can’t sort the tree model’s output directly. They’d be handed TreeListRows, and even if they unwrapped them, sorting the flat list by size would pull children away from their parents.

TreeListRowSorter does the tree part. You give it the view’s sorter, and given two rows it walks them up to the level they share, compares the Nodes there with the inner sorter, and keeps each child under its parent. This is why passthrough has to be off: the sorter needs the rows to find the parents.

let sorter = column_view
    .sorter()
    .and_downcast::<gtk::ColumnViewSorter>()
    .unwrap();
let row_sorter = gtk::TreeListRowSorter::new(Some(sorter.clone()));
let sort_model = gtk::SortListModel::new(Some(tree.clone()), Some(row_sorter));
let selection = gtk::MultiSelection::new(Some(sort_model));
column_view.set_model(Some(&selection));

The order of the stack matters. The SortListModel sits above the tree model, sorting the flattened rows, so every level comes out sorted: the years, the trips inside each year, the photos inside each trip. The other place a sort model could go is under each folder’s store, one per folder. Then a header click would have to reach every one of them, including the ones for folders that aren’t open. One sorter at the top is simpler.

Sorted by Size, descending, with everything open, a scratch test that dumps the rows gives this (v is open, > is closed):

v 2025 55.5 MB
  v Japan 47.3 MB
      DSCF0412.RAF 24.0 MB
      ...
  v Garden 6.1 MB
      ...
    IMG_0934.HEIC 2.1 MB
v 2024 48.5 MB
  v Tasmania 44.5 MB
  ...
v 2026 37.8 MB

A folder’s size is the total of everything under it, so the biggest year comes first, the biggest trip inside it, and the biggest photo inside that. The loose photo in 2025 sorts in with the trips, because at that level it’s just another child.

Since both views share the selection model, the outline sorts however the table is sorted. It has no headers of its own, so you can’t change the sort from there.


Expanding everything

autoexpand sounds like an Expand all switch. It’s narrower than that: the docs for set_autoexpand say it expands rows as they’re added, so on a model that already exists, turning it on leaves the current rows as they are.

Expand all is a loop over tree positions instead:

let mut position = 0;
while let Some(row) = model.row(position) {
    row.set_expanded(true);
    position += 1;
}

Expanding the row at position i inserts its children at i + 1, and the loop walks straight into them, so one pass opens every level. These are tree positions, not sorted ones, which is why it asks the tree model and not the selection.

Collapse all walks backwards, from the last row to the first. Collapsing a row removes the rows after it, and going backwards means those are always rows the loop has already been past.


Adding a photo, and the sort going stale

Add photo puts a new 3 MB photo into the selected folder, or the selected photo’s folder, or the Inbox. It goes through the folder’s own store, and Node’s append adds the size to that folder and every folder above it. The labels bound to size update by themselves, since a property change notifies the bindings.

The sort model doesn’t follow along. SortListModel still has no watch-items, so a folder total that changes under a size sort leaves that folder where it was.

To see how bad that gets I took out the line that fixes it, closed the Christmas folder in 2024, and added three photos to it. That takes 2024 from 48.5 MB to 57.5 MB, past 2025. The years stayed in their old order, 2025 still on top. Then I opened Christmas:

      NEW_0001.jpg 3.0 MB
v 2025 55.5 MB
  v Japan 47.3 MB
  ...
v 2024 57.5 MB
  v Tasmania 44.5 MB
  ...
  v Christmas 13.0 MB
      NEW_0002.jpg 3.0 MB
      NEW_0003.jpg 3.0 MB
      IMG_1532.HEIC 2.1 MB
      IMG_1540.HEIC 1.9 MB

One of the new photos landed in the first row of the list, above every year and nowhere near its own folder. Opening Christmas inserted three rows, and the sort model placed each one by comparing against the current totals. Those disagree with the order it was already holding, and in a binary search an inconsistent order can send an item almost anywhere. It’s displaying a list that’s no longer sorted and inserting into it as though it were.

The obvious fix is the one from the items-changed post: have the store emit items_changed(pos, 1, 1) for the folder whose total changed, so the sort model re-places it. In a tree that doesn’t work. I emitted it on the root store for 2026 with 2026 open, and the sort model did move it, but the row came back collapsed. TreeListModel reads a removal and an insertion and makes a new row for the new item, closed, even though it’s the same object. Every folder up the chain from a new photo would snap shut each time you added one.

So the example goes back to the workaround that post replaced. After the append, the button tells the sorter its results may all be different:

folder.append(&photo);
sorter.changed(gtk::SorterChange::Different);

Every row is re-sorted in place and nothing collapses. With that line back, the same three photos put 2024 on top, and the new photos sit inside Christmas in size order.

I don’t love it. It’s a full re-sort per added photo, which is the cost the items-changed post set out to remove, and it only helps changes made through this button. A sync that changed a folder’s contents behind the app’s back would have to make the same call. For a photo library the size of mine that’s fine. I’d want a better answer before putting this on a library of fifty thousand photos, and I don’t have one yet.

It’s also the same call the last post found re-sorts correctly only because ColumnViewSorter keeps no sort keys of its own. Here it’s wrapped in a TreeListRowSorter, and it re-sorted correctly in every case I tried, but that’s still undocumented behaviour I’m leaning on.


Sharp edges

The closure runs more often than you’d think. It runs to draw arrows and again on every expand. Keep it cheap and return the same model each time, which means the folder owns its children.

Returning None is permanent. A folder that’s empty today should still return an empty model.

Keep passthrough off if you sort. TreeListRowSorter needs the rows to keep children under their parents, and the expander needs them for depth either way.

Put the sort model above the tree. One SortListModel over the TreeListModel sorts every level, and the column headers drive it like they did on a flat table.

autoexpand only applies to rows added later. Expand all is a loop over tree positions.

A changed total needs a re-sort. items_changed on a child model collapses the row, so sorter.changed(gtk::SorterChange::Different) it is, until I find something better.


Next up

Nesting is one way to group a library. The other is to leave it flat and put headings in it: all the 2025 photos under a “2025” header in a single scrolling list, with no folders to open. The next post does that with GtkSectionModel and a header factory, which is a much shorter job than this one was.

The runnable version of this example is in the companion repo: cd 08-trees && cargo run, from a terminal if you want the closure log. One widget at a time. See you in the next one.

Assisted by Claude Code (claude-opus-5-5). The experiments, bugs and conclusions are mine. How I work with AI tools is in The AI pair programmer.