Home > Blockchain >  ellipsis expansion fyne NewVBox
ellipsis expansion fyne NewVBox

Time:10-18

I'm trying to create a Fyne vertical box with a series of buttons but can't figure out the basic mechanism. I think this is a Go question, not a Fyne question, something I don't understand about go.

Here is a minimal program to show what I mean:

package main

import (
    "fmt"

    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/widget"
)

func main() {

    a := app.New()
    w := a.NewWindow("Button List")

    btn0 := widget.NewButton("button 0", func() {
        fmt.Println("Pressed 0")
    })
    btn1 := widget.NewButton("button 1", func() {
        fmt.Println("Pressed 1")
    })

    btns := []*widget.Button{btn0, btn1}

    vbox := container.NewVBox(
        // does work
        btns[0],
        btns[1],
        // doesn't work
        // btns...,
    )

    w.SetContent(
        vbox,
    )
    w.ShowAndRun()
}

My understanding is that the argument btns... should produce the same effect as the list of arguments btn[0], btn[1], but it apparently doesn't. If I comment out the lines

    btn[0], 
    btn[1],

and uncomment the line

    btns...

I get the error message

cannot use btns (type []*"fyne.io/fyne/v2/widget".Button) as type []fyne.CanvasObject in argument to container.NewVBox

So, my newbie questions:

  • whats going on here, i.e., why doesn't btns... work?
  • what should I be using as the argument to NewVBox instead?

CodePudding user response:

To do what you're wanting to do here you need to modify the slice of *widget.Button to be a slice of fyne.CanvasObject.

When spreading into a variadic parameter like this, the types have to match exactly to what the variadic parameter is expecting. This means the type needs to be the interface itself and not a type that implements the interface.

In your case, the following will work:

btns := []fyne.CanvasObject{btn0, btn1}
vbox := container.NewVBox(btns...)
  • Related