简体   繁体   中英

How to return Row and Col using Grid in Go Fyne?

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:)

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()
}

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)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM