Replies: 2 comments 2 replies
-
The typing system in Go does unfortunately not seem to be smart enough to tell that a slice of a |
Beta Was this translation helpful? Give feedback.
-
Thank you very much for your answer, it pointed me in the direction of a solution I rather like. The slice of someCO := make([]fyne.CanvasObject, 5)
for i := range someCO {
i := i // save local copy to use in closure
someCO[i] = widget.NewButton(fmt.Sprintf("CO%d", i), func() { buttonCB(i) })
}
contCOBtn := container.NewHBox(someCO...) but then trying to access a button-specific field fails, requiring a type assertion: // fails:
// someCO[0].Importance undefined (type fyne.CanvasObject has no field or method Importance)
someCO[0].Importance = widget.HighImportance
// works
someCO[1].(*widget.Button).Importance = widget.HighImportance Rather than declaring the slice as a func NewHBoxGen[T fyne.CanvasObject](objects ...T) *fyne.Container {
objCO := make([]fyne.CanvasObject, len(objects))
for i := range objCO {
objCO[i] = fyne.CanvasObject(objects[i])
}
return container.NewHBox(objCO...)
} and just use it directly as the type arg is inferred: contBtn := NewHBoxGen(someButtons...)
someLabels := make([]*widget.Label, 5)
for i := range someLabels {
someLabels[i] = widget.NewLabel(fmt.Sprintf("L%d", i))
}
contLab := NewHBoxGen(someLabels...) By moving the conversion in a helper function we can easily extend this behaviour to all the containers: func toCO[T fyne.CanvasObject](objects ...T) []fyne.CanvasObject {
objCO := make([]fyne.CanvasObject, len(objects))
for i := range objCO {
objCO[i] = fyne.CanvasObject(objects[i])
}
return objCO
}
func NewHBoxGen[T fyne.CanvasObject](objects ...T) *fyne.Container {
return container.NewHBox(toCO(objects...)...)
}
func NewVBoxGen[T fyne.CanvasObject](objects ...T) *fyne.Container {
return container.NewVBox(toCO(objects...)...)
} Or you can call the helper function directly: contBtn := container.NewHBox(toCO(someButtons...)...) There is a small overhead related to the slice conversion, but as I said in my use case the slices are short and stable, so I'm quite happy with this solution, so thank you again. Cheers! |
Beta Was this translation helpful? Give feedback.
-
Hello,
I'm trying to create a layout with a dynamic number of widgets in it.
The number of widgets will be small and will change slowly, being able to do so at startup would be ok if needed.
An app like this does what I need, except for the hard coded layout of course:
I tried something like this:
but I get the following error:
cannot use someButtons (variable of type []*"fyne.io/fyne/v2/widget".Button) as []fyne.CanvasObject value in argument to container.NewHBox
.Is there a workaround?
Thank you very much,
Peter
Beta Was this translation helpful? Give feedback.
All reactions