Skip to content

Layout

Container Widget

Castella has three container widgets for UI layout; Column, Row and Box.

Column

Column aligns child elements vertically like this and the code looks like this.

Column(
  Text("First", font_size=24),
  Text("Second", font_size=24),
  Text("Third", font_size=24),
)

Row

Row aligns child elements horizontally like this and the code is this.

Row(
  Text("First", font_size=24),
  Text("Second", font_size=24),
  Text("Third", font_size=24),
)

Box

Box takes only one child. If the child size is bigger than the parent box, the parent box provides scrollbars automatically. (By the way, if you set scrollable=True for Column or Row, a scrollbar will appear when the child elements do not fit within the view.)

Box(
  Text("Content", font_size=24).fixed_size(400, 400),
)

Size Policy

Each widget has size policies for each width and height. There are three types of policies that can be specified.

  • Expanding: maximum size that will fit in the parent widget
  • Fixed Size: specified size
  • Content: size according to the content (e.g., for text, according to the size of that text)

The default policy is different depending on the kind of widget, but it is basically “Expanding” for both width and height.

For example, in the Row example above, the width policy of each Text widget is “Expanding" and the height policy is "Expanding”.

Row(
  Text("First", font_size=24),
  Text("Second", font_size=24),
  Text("Third", font_size=24),
)

In this case, the width of each Text widget is expanded to the width of the parent Row widget and share their width equally, and the height of each Text widget is expanded to the height of the parent Row widget.

The code above is same with the code below written without omission of the size policy setting.

Row(
  Text("First", font_size=24).WidthPolicy(SizePolicy.Expanding)
                             .HeightPolicy(SizePolicy.Expanding),
  Text("Second", font_size=24).WidthPolicy(SizePolicy.Expanding)
                              .HeightPolicy(SizePolicy.Expanding),
  Text("Third", font_size=24).WidthPolicy(SizePolicy.Expanding)
                             .HeightPolicy(SizePolicy.Expanding),
)

Flex

By specifying "flex" you can specify each widget's occupied ratio for the overall size in the parent widget.

Row(
  Text("First", font_size=24).flex(1),
  Text("Second", font_size=24).flex(2),
  Text("Third", font_size=24).flex(1),
)

In this example above, the width of the entire row is divided in the ratio 1:2:1.

Mix of various size policies

Of course, you can mix multiple size policies for the children of a single parent widget.

Row(
  Text("First", font_size=24).fixed_size(100, 50),
  Text("Second", font_size=24).flex(2),
  Text("Third", font_size=24).flex(1),
)

In this example, the first element is displayed at the specified fixed size. The remaining two child elements share the remaining width in 2:1 ratio.