Skip to content

Tree

The Tree widget in Fyne is used to display hierarchical data, such as file explorers, category lists, or nested menus. It allows expanding and collapsing nodes for better navigation.

Show Code
package main
import (
"fmt"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
)
func main() {
a := app.New()
w := a.NewWindow("Tree Collection")
// Define the data for the tree
data := map[string][]string{
"": {"Fruits", "Vegetables"}, // root nodes
"Fruits": {"Apple", "Banana", "Mango"},
"Apple": {"Red Apple", "Green Apple"}, // nested children
"Banana": {"Yellow Banana"},
"Vegetables": {"Carrot", "Broccoli"},
}
// Create the tree
tree := widget.NewTree(
func(uid widget.TreeNodeID) []widget.TreeNodeID { // children
return data[uid]
},
func(uid widget.TreeNodeID) bool { // is branch?
children, ok := data[uid]
return ok && len(children) > 0
},
func(branch bool) fyne.CanvasObject { // create template
return widget.NewLabel("Template")
},
func(uid widget.TreeNodeID, branch bool, obj fyne.CanvasObject) { // update
obj.(*widget.Label).SetText(uid)
},
)
// Handlers
tree.OnSelected = func(uid widget.TreeNodeID) {
fmt.Println("Selected:", uid)
}
tree.OnBranchOpened = func(uid widget.TreeNodeID) {
fmt.Println("Branch opened:", uid)
}
tree.OnBranchClosed = func(uid widget.TreeNodeID) {
fmt.Println("Branch closed:", uid)
}
// Expand root
tree.OpenAllBranches()
w.SetContent(container.NewStack(tree))
w.Resize(fyne.NewSize(400, 300))
w.ShowAndRun()
}