Go言語 - WALKでGUI - ListBox
ListBoxの使用例。ウィンドウ上がListBox。
表示項目をstringのスライスにしてModelフィールドに置くことで表示させます。各項目はクリックおよびダブルクリックでイベントが発生します。
ボタンクリックで項目を追加しています。方法はListBox.Model()で項目リストを取得します。これはインターフェース型なのでストリングのスライスに型アサーションを実施してappend()で項目を追加後、Modelフィールドに再設定します。
package main import ( "github.com/lxn/walk" . "github.com/lxn/walk/declarative" ) import ( "fmt" "os" ) type MyMainWindow struct { *walk.MainWindow list *walk.ListBox edit *walk.TextEdit items []string } func main() { mw := &MyMainWindow {} mw.items = []string{ "one", "two", "three", "four", "five", } MW := MainWindow{ AssignTo: &mw.MainWindow, Title: "ListBoxテスト", MinSize: Size {300, 200}, Size : Size {300, 400}, Layout: VBox {}, Children: []Widget { ListBox{ AssignTo: &mw.list, Model: mw.items, OnCurrentIndexChanged: mw.curIdxChanged, OnItemActivated: mw.itemActiveted, }, TextEdit { AssignTo: &mw.edit, }, PushButton { Text: "Push", OnClicked: mw.pbClicked, }, }, } if _, err := MW.Run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func (mw *MyMainWindow) curIdxChanged() { idx := mw.list.CurrentIndex() if idx >= 0 { // 項目を追加するとidx=-1のイベントが発生する為 s := fmt.Sprintf("Event: Index %d is selected\r\n", idx) mw.edit.AppendText(s) } } func (mw *MyMainWindow) itemActiveted() { s := fmt.Sprintf("Event: Index %d is activated(DBL clicked)\r\n", mw.list.CurrentIndex()) mw.edit.AppendText(s) } func (mw *MyMainWindow) pbClicked() { m := mw.list.Model().([]string) // interface{} -> []string m = append(m, "追加項目") _ = mw.list.SetModel(m) }