向List小部件动态添加项



我正在使用名为Fyne的GUI框架。如何动态地将项添加到List小部件使用的数组中?代码:

var componentsList = []string{"test1: test1"}
func main() {
app := app.New()
window := app.NewWindow("Delta Interface")
componentsTree := widget.NewList(
func() int {
return len(componentsList)
},
func() fyne.CanvasObject {
return widget.NewLabel("template")
},
func(i widget.ListItemID, o fyne.CanvasObject) {
o.(*widget.Label).SetText(componentsList[i]) // i need to update this when componentsList was updated
})
nameEntry := widget.NewEntry()
typeEntry := widget.NewEntry()
form := &widget.Form{
Items: []*widget.FormItem{
{Text: "Name", Widget: nameEntry},
{Text: "Type", Widget: typeEntry}},
OnSubmit: func() {
componentsList = append(componentsList, nameEntry.Text+": "+typeEntry.Text) // append an item to componentsList array
},
}
layout := container.New(layout.NewGridWrapLayout(fyne.NewSize(350, 500)), componentsTree, form)
window.SetContent(layout)
window.Resize(fyne.NewSize(800, 600))
window.ShowAndRun()
}

我在上面代码的注释中写了我需要做的事情:

  1. 当componentsList被更新时,我需要更新这个。
  2. 添加一个项目到componentsList数组

更新List呈现的数据后,只需调用Refresh()。因此,只需将OnSubmit函数更新为:

OnSubmit: func() {
componentsList = append(componentsList, nameEntry.Text+": "+typeEntry.Text)
componentsTree.Refresh()
},

最新更新