4 Placing widgets
Jakub Sobon edited this page 2020-11-14 01:29:24 -05:00

Doc Status

Apart from establishing the terminal layout, containers are meant to hold widgets. Each container can hold exactly one widget. Containers that have widgets cannot have sub-containers.

Container is responsible for allocating virtual canvas for the widget that is in accordance to the options the widget provided. See the Widget API for more details on widget options. If the widget specifies maximum canvas size or ratio, there might be an empty space left inside the container and around the widget. If that happens, the widget alignment options can help to visually align widgets inside a container. Widgets that don't specify these options automatically stretch to the full size of the container unless the container has padding specified.

container.PlaceWidget

The container.PlaceWidget option places the provided widget into the container.

/images/container-api/placed_button.png

The following code places a button widget inside a container as shown above:

t, err := tcell.New()
if err != nil {
    panic(err)
}
defer t.Close()

b, err := button.New("hello world", func() error {
    return nil
},
)
if err != nil {
    return fmt.Errorf("button.New => %v", err)
}

c, err := container.New(
    t,
    container.PlaceWidget(b),
)
if err != nil {
    return fmt.Errorf("container.New => %v", err)
}

Widget alignment options

The following options can be used to align a widget within the container both horizontally and vertically.

/images/container-api/aligned_button.png

The following code aligns the button widget into the top right corner as shown above:

t, err := tcell.New()
if err != nil {
    panic(err)
}
defer t.Close()

b, err := button.New("hello world", func() error {
    return nil
},
)
if err != nil {
    return fmt.Errorf("button.New => %v", err)
}

c, err := container.New(
    t,
    container.PlaceWidget(b),
    container.AlignHorizontal(align.HorizontalRight),
    container.AlignVertical(align.VerticalTop),
)
if err != nil {
    return fmt.Errorf("container.New => %v", err)
}

container.AlignHorizontal

The container.AlignHorizontal option is used to specify horizontal alignment for the widget. Refer to the Align API for alignment options.

container.AlignVertical

The container.AlignVertical option is used to specify vertical alignment for the widget. Refer to the Align API for alignment options.