如何在 golang 的 fyne 中循环 fyne.CanvasObject

how to loop over fyne.CanvasObject in fyne in golang

问题是。我有 NewVScrollNewVScroll 我有 NewVBoxLayoutNewVBoxLayout 我有 NewButton问题是当我按下 NewButton 它应该循环 NewVScroll 然后循环 NewVBoxLayout 找到 NewButton 。但我不知道如何在 fyne 中做到这一点,因为我无法循环 var v1 fyne.CanvasObject

错误是:cannot range over v1 (variable of type fyne.CanvasObject)

这是代码

package main

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/widget"
)

var cEntries *fyne.Container

func FindObject(object fyne.CanvasObject, objects []fyne.CanvasObject) (int, bool) {
    for k1, v1 := range objects {
        for _, v2 := range v1 {// the problem is here. i can't loop over fyne.CanvasObject
            if v2 == object {
                return k1, true
            }
        }
    }
    return 0, false
}

func w1() *fyne.Container {
    wb := widget.NewButton("", nil)

    wb.OnTapped = func() {
        index, isin := FindObject(wb, cEntries.Objects)
        fmt.Println(index, isin)
    }

    return container.New(layout.NewVBoxLayout(), wb)
}

func main() {
    a := app.New()
    w := a.NewWindow("")

    wbAdd := widget.NewButton("+", nil)
    cEntries = container.New(layout.NewVBoxLayout(), wbAdd, w1())

    wbAdd.OnTapped = func() {
        cEntries.Add(w1())
    }

    wsEntries := container.NewVScroll(cEntries)

    w.SetContent(wsEntries)
    w.ShowAndRun()
}

该对象是一个容器,因此通常您可以迭代 v1.(*fyne.Container).Objects

但是看起来您可以避免在代码中循环,因为按钮总是引用添加按钮时设置的索引 - 因此您可以将当前的 index(长度)传递给 w1 然后增加它。

你不需要循环 NewVBoxLayout 因为它是 fyne.CanvasObject 然后如果你想要知道包含此小部件 NewButton 的布局索引,您只需在中搜索 NewVBoxLayout 即可NewVScroll 这是代码

package main

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/widget"
)

var cEntries *fyne.Container

func FindObject(object fyne.CanvasObject, objects []fyne.CanvasObject) (int, bool) {
    for k1, v1 := range objects {
        if v1 == object {
            return k1, true
        }
    }
    return 0, false
}

func w1() *fyne.Container {
    wb := widget.NewButton("", nil)
    c := container.New(layout.NewVBoxLayout(), wb)
    wb.OnTapped = func() {
        index, isin := FindObject(c, cEntries.Objects)
        fmt.Println(index, isin)
    }

    return c
}

func main() {
    a := app.New()
    w := a.NewWindow("")

    wbAdd := widget.NewButton("+", nil)
    cEntries = container.New(layout.NewVBoxLayout(), wbAdd, w1())

    wbAdd.OnTapped = func() {
        cEntries.Add(w1())
    }

    wsEntries := container.NewVScroll(cEntries)

    w.SetContent(wsEntries)
    w.ShowAndRun()
}

在这段代码中看到您创建了处理按钮的容器,然后搜索包含此按钮的容器