演示动画
功能
- 动态添加一行控件
- 最多添加5行
- 可添加文件夹路径
- 动态删除本行控件
全部代码
package main
import (
"fmt"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/widget"
"github.com/flopp/go-findfont"
"os"
"strconv"
"strings"
)
func init() {
fontPaths := findfont.List()
for _, path := range fontPaths {
if strings.Contains(path, "msyh.ttf") || strings.Contains(path, "simhei.ttf") || strings.Contains(path, "simsun.ttc") || strings.Contains(path, "simkai.ttf") || strings.Contains(path, "STHeiti Medium.ttc") || strings.Contains(path, "Songti.ttc") {
os.Setenv("FYNE_FONT", path)
break
}
}
}
type MyWidget struct {
id int
myWidgets []fyne.CanvasObject
}
var (
l11, l12, l41 *widget.Label
b31 *widget.Button
sid int
)
var myWidgetList []*MyWidget
var cc = &fyne.Container{}
func main() {
myApp := app.NewWithID("com.xiantianshizhong.gogyne")
w := myApp.NewWindow("竖向中间位置动态添加一行控件")
w.Resize(fyne.NewSize(800, 400))
w.CenterOnScreen()
l11 = widget.NewLabel("添加控件行数:")
l12 = widget.NewLabel("0")
b31 = widget.NewButton("添加控件", func() {
addContainer(w)
})
l41 = widget.NewLabel("其他控件...")
refreshlayout(w)
w.ShowAndRun()
}
func addContainer(w fyne.Window) {
n := len(myWidgetList)
if n < 5 {
ll1 := widget.NewLabel("")
ee := widget.NewEntry()
ll2 := widget.NewLabel("请点击右边按钮选择文件夹...")
bb1 := widget.NewButton("选择文件夹", func() {
dialog.NewFolderOpen(func(uri fyne.ListableURI, err error) {
if uri != nil {
ll2.SetText(uri.Path())
}
}, w).Show()
})
var bb2 *widget.Button
bb2 = widget.NewButton("删除本行", func() {
var ctemp []*MyWidget
for _, c := range myWidgetList {
b, _ := c.myWidgets[4].(*widget.Button)
if bb2 == b {
fmt.Println(c.id)
continue
}
ctemp = append(ctemp, c)
}
myWidgetList = ctemp
refreshlayout(w)
})
sid++
myw := new(MyWidget)
myw.id = sid
myw.myWidgets = []fyne.CanvasObject{ll1, ee, ll2, bb1, bb2}
myWidgetList = append(myWidgetList, myw)
refreshlayout(w)
}
}
func refreshlayout(w fyne.Window) {
n := len(myWidgetList)
l12.SetText(strconv.Itoa(n))
cc = &fyne.Container{}
cc.Objects = append(cc.Objects, container.NewHBox(l11, l12))
for i, c := range myWidgetList {
v, _ := c.myWidgets[0].(*widget.Label)
v.SetText(strconv.Itoa(i + 1))
cc.Objects = append(cc.Objects, container.NewHBox((c.myWidgets)...))
}
cc.Objects = append(cc.Objects, b31, l41)
w.SetContent(container.NewVBox(cc.Objects...))
}