I am having a hard time figuring out how to return the rows and cols of the grid when the button is pressed. Here I have a simple code in Go:
package main
import (
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
)
func main() {
a := app.New()
w := a.NewWindow("Grid")
content := container.NewGridWithColumns(3)
for y := 0; y < 3; y {
for x := 0; x < 3; x {
btn := widget.NewButton("", nil) // returns row and col of the grid
content.Add(btn)
}
}
w.SetContent(content)
w.ShowAndRun()
}
I hope you guys can help :)
CodePudding user response:
Dropped old answer
Can extend widget.Button to achieve this.
package main
import (
"fmt"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
)
type MyButton struct {
*widget.Button
X, Y int
}
func main() {
a := app.New()
w := a.NewWindow("Grid")
content := container.NewGridWithColumns(3)
for y := 0; y < 3; y {
for x := 0; x < 3; x {
//btn := widget.NewButton(fmt.Sprintf("Button %d_%d", y, x), nil)
btn := &MyButton{
Button: widget.NewButton(fmt.Sprintf("Button %d_%d", y, x), nil),
X: x,
Y: y,
}
btn.OnTapped = func() {
fmt.Printf("%s Pressed Y:%d X:%d \n",
btn.Text,
btn.Y,
btn.X)
}
content.Add(btn)
}
}
w.SetContent(content)
w.ShowAndRun()
}
CodePudding user response:
As the function is defined inline you can simply capture the variables.
for y := 0; y < 3; y {
savedY := y
for x := 0; x < 3; x {
savedX := x
btn := widget.NewButton("",
func() {
log.PrintLn(“Saved”, savedX, savedY)
})
content.Add(btn)
}
}