英文:
fyne create rows in a container from a slice of containers
问题
我需要一个名为"rows"的切片,其中包含一些fyne.Container结构体。然后我需要将它们显示为窗口中的行。
我尝试了以下代码:
rows := []*fyne.Container{}
rows = append(
rows,
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
)
w.SetContent(
container.New(
layout.NewGridLayout(1),
rows...
),
)
但是我得到了以下错误信息:
无法将rows(类型为[]*fyne.Container)作为container.New的参数类型[]fyne.CanvasObject使用
我不明白为什么如果我这样做:
w.SetContent(
container.New(
layout.NewGridLayout(1),
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
),
)
它可以正常工作...传递单个结构体或[]type不应该是一样的吗?
谢谢!
英文:
I need to have a slice called rows containing a number of fyne.Container structs.
Then I need to show them all as rows in a window.
I tried doing this:
rows := []*fyne.Container{}
rows = append(
rows,
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
)
w.SetContent(
container.New(
layout.NewGridLayout(1),
rows...
),
)
but I get
> cannot use rows (type []*fyne.Container) as type []fyne.CanvasObject in argument to container.New
And I don't understand why if I do this:
w.SetContent(
container.New(
layout.NewGridLayout(1),
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
),
)
It works fine... Shouldn't it be the same passing individual structs or a []type...?
Thanks!
答案1
得分: 2
该方法期望一个 fyne.CanvasObject
的切片,这是 fyne.Container
结构体实现的一个接口。
结构体类型的切片不能替代接口类型的切片,即使结构体类型满足该接口。
你的切片应该是接口类型而不是结构体类型。然后,你可以将满足该接口的对象追加到该切片中:
rows := []fyne.CanvasObject{}
rows = append(
rows,
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
)
英文:
The method expects a slice of fyne.CanvasObject
s, which is an interface that the struct fyne.Container
implements.
A slice of a struct type cannot be used in place of a slice of an interface type, even if the struct type satisfies the interface.
Your slice should be of the interface type not the struct type. You can then append objects that fulfill the interface to that slice:
rows := []fyne.CanvasObject{}
rows = append(
rows,
container.New(
layout.NewGridLayout(4),
widget.NewLabel("Trigger"),
widget.NewLabel("Text"),
widget.NewLabel("Enter"),
widget.NewLabel("Active"),
),
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论