fyne input失去焦点,触发事件函数
package mainimport ("fmt""fyne.io/fyne/v2/app""fyne.
package main
import (
"fmt"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/widget"
"log"
)
// FocusEntry 自定义 Entry 组件,支持失去焦点事件
type FocusEntry struct {
widget.Entry
onFocusLost func()
}
// NewFocusEntry 创建新的自定义 Entry
func NewFocusEntry() *FocusEntry {
entry := &FocusEntry{}
entry.ExtendBaseWidget(entry)
return entry
}
// SetOnFocusLost 设置失去焦点回调函数
func (e *FocusEntry) SetOnFocusLost(callback func()) {
e.onFocusLost = callback
}
// FocusLost 重写 FocusLost 方法
func (e *FocusEntry) FocusLost() {
e.Entry.FocusLost() // 调用父类方法
if e.onFocusLost != nil {
e.onFocusLost() // 执行自定义回调
}
}
func main() {
myApp := app.New()
myWindow := myApp.NewWindow("form widget")
entry := NewFocusEntry()
textArea := widget.NewMultiLineEntry()
entry.SetOnFocusLost(func() {
fmt.Printf("输入框失去焦点,内容: %s\n", entry.Text)
// 这里可以添加验证逻辑
if entry.Text == "" {
fmt.Println("错误: 内容不能为空!")
} else if len(entry.Text) < 3 {
fmt.Println("错误: 内容至少需要3个字符!")
} else {
fmt.Println("输入有效!")
}
})
form := &widget.Form{
Items: []*widget.FormItem{
{Text: "entry", Widget: entry},
},
OnSubmit: func() {
log.Println("form submitted", entry.Text)
log.Println("multiline:d", textArea.Text)
//myWindow.Close()
},
}
form.Append("Text", textArea)
myWindow.SetContent(form)
myWindow.ShowAndRun()
}