Search code examples
gofyne

Dynamically update fyne tree widget


need help to update a Tree widget at runtime, as suggested here fyne issue seems that using Refresh() function on the widget it will sync the data changes stored in the list map, here is the code:

package main

//______________________________________________________________________________

import (
    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/layout"
    "fyne.io/fyne/v2/widget"

    dbg "github.com/fatih/color"
)

//______________________________________________________________________________

var content *fyne.Container
var tree *widget.Tree
var list map[string][]string

//______________________________________________________________________________

func main() {
    myApp := app.New()
    myWindow := myApp.NewWindow("List")
    makeTree()
    top := widget.NewLabel("Items' list::")
    bottom := widget.NewButton("Update list", updateList)
    content = container.New(layout.NewBorderLayout(top, bottom, nil, nil),
        top,
        tree,
        bottom,
    )

    myWindow.SetContent(content)
    myWindow.Resize(fyne.NewSize(480, 600))
    myWindow.ShowAndRun()
}

//______________________________________________________________________________

func makeTree() {
    list = map[string][]string{
        "":  {"A"},
        "A": {"B", "D"},
        "B": {"C"},
        "C": {"abc"},
        "D": {"E"},
        "E": {"F", "G"},
    }

    tree = widget.NewTreeWithStrings(list)
    tree.OnSelected = func(id string) {
        dbg.Green("Tree node selected: %s", id)
    }
    tree.OnUnselected = func(id string) {
        dbg.Green("Tree node unselected: %s", id)
    }

    tree.OpenAllBranches()
}

//______________________________________________________________________________

func updateList() {
    dbg.Green("UpdateList")

    list = map[string][]string{
        "":  {"A"},
        "A": {"B"},
        "B": {"C"},
    }

    tree.Refresh()
}

Thanks


Solution

  • The NewTreeWithStrings is a static helper function, so does not really update the way you want. If you can use NewTree then you can point to your data structure and it will auto update.