gofyne

Golang Fyne. How to get and update widget within another conainer?


I'm trying to update widgets when a button is clicked, but the button and the widgets I want to update are in different containers.

How should I handle this? Do I need to use some kind of global variable to store all my widgets?

package ui

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

func NewApp() fyne.Window {
    a := app.New()
    a.Settings().SetTheme(theme.LightTheme())
    w := a.NewWindow("UI")
    w.CenterOnScreen()
    w.Resize(fyne.NewSize(840, 560))

    mainContainer := container.NewHSplit(LeftContainer(), RightContainer())
    mainContainer.Offset = 0.3

    w.SetContent(mainContainer)
    w.SetMaster()

    return w
}

func LeftContainer() *fyne.Container {
    entry := widget.NewMultiLineEntry()
    entry.SetPlaceHolder("JSON")

    check := widget.NewCheck("Online", nil)
    check2 := widget.NewCheck("Analogs", nil)

    btn := widget.NewButton("Start", nil)

    btn.OnTapped = func() {
        // How to update timer that lives in right container?
    }

    return container.NewBorder(nil, container.NewVBox(check, check2, btn), nil, nil, entry)
}

func RightContainer() *fyne.Container {
    content := container.NewStack()
    timer := widget.NewLabel("Timer")

    return container.NewBorder(
        container.NewVBox(container.NewHBox(layout.NewSpacer(), timer), widget.NewSeparator()),
        nil,
        nil,
        nil,
        content)
}

I've found a quite similar question here, but I still don't fully understand. How can I determine the index of the element I want to update?


Solution

  • Traversing containers by indexing isn’t the best way because you lose all type safety.

    In your example the easiest way is to return the item to be updated from the left/right setup functions as well as the container.

    Version two of that might be to have an app object that is defined to have those two widgets set as fields in the struct so they can be accessed later.

    Depending on what sort of updates you’re doing you could also look at data binding so the widgets automatically update when the source changes.