lxn / walk

A Windows GUI toolkit for the Go Programming Language
Other
6.8k stars 885 forks source link

how to add a tabpage dynamically to tabwidget? #677

Closed chenqinghe closed 4 years ago

chenqinghe commented 4 years ago

here is my code:

package main

import (
    //"fmt"

    "fmt"
    //"github.com/lxn/walk"
    "github.com/lxn/walk"
    . "github.com/lxn/walk/declarative"
)

func main() {
    var tw *walk.TabWidget
    var mw *walk.MainWindow
    MainWindow{
        AssignTo: &mw,
        MinSize:  Size{600, 400},
        Layout:   VBox{},
        Children: []Widget{
            PushButton{
                Text: "add tab",
                OnClicked: func() {
                    page, err := walk.NewTabPage()
                    if err != nil {
                        walk.MsgBox(nil, "ERROR", err.Error(), walk.MsgBoxIconError)
                        return
                    }
                    tabCount := tw.Pages().Len()
                    page.SetTitle(fmt.Sprintf("tab%d", tabCount+1))

                    te,err:= walk.NewTextEdit(page)
                    if err!=nil {
                        fmt.Println(err)
                    }
                    if err:=page.Children().Add(te);err!=nil {
                        fmt.Println("add TextEdit error:",err)
                    }

                    tw.Pages().Add(page)
                    if err := tw.SetCurrentIndex(tw.Pages().Len() - 1); err != nil {
                        fmt.Println(err)
                    }

                },
            },
            TabWidget{
                AssignTo: &tw,
                Pages: []TabPage{
                    TabPage{
                        Title: "tab1",
                        Content: TextEdit{
                            Text: "this is tab1",
                        },
                    },
                    TabPage{
                        Title: "tab2",
                        Content: TextEdit{
                            Text: "this is tab2",
                        },
                    },
                },
            },
        },
    }.Run()
}

The code do create a new tabpage and append to tabwidget, but its content is empty. I dont know how to figure out the problem, please help me, thank you!

chenqinghe commented 4 years ago

After a long time research and experiment, finally i find that tabpage MUST have a layout, so just add the code:


page.SetLayout(walk.NewVBoxLayout())

will solve the problem.

goexc commented 3 years ago

How to resolve the error ? "add TextEdit error: cannot insert same widget multiple times".

goexc commented 3 years ago

page.Children().Contains(te) replace page.Children().Add(te) can resolve this error.