rgargente
rgargente

Reputation: 1840

How to automatically set the height of a horizontal BoxLayout

So I have some simple layout like this:

<MyWidget>:
   orientation: 'vertical'
   Label:
       font_size: 20
       text: 'Label 1'
       size: self.texture_size
       size_hint_y: None
   BoxLayout:
       id: 'stubborn_layout'
       size_hint_y: None
       TextInput:
           multiline: False
           size_hint_y: None
           height: self.minimum_height
       Label:
           text: 'things'
           size_hint_x: None
           size_hint_y: None
           size: self.texture_size
           padding_x: 6
           padding_y: 6
   Label:
       font_size: 20
       text: 'Label 2'
       size: self.texture_size
       size_hint_y: None

The heights of the widgets inside stubborn_layout are computed nicely. However, stubborn_layout itself has a default height of 100. What I want is to have it automatically set to whatever size the children have. I can just set it manually to the right height but that's not particularly elegant or maintainable. Can I do that?

Or maybe my approach is wrong... but I can't find any other layout that suits me better for this case.

Upvotes: 1

Views: 559

Answers (1)

ODiogoSilva
ODiogoSilva

Reputation: 2414

You could go about this in two ways. If you want to stick with a BoxLayout, you could bind its height to one child, the Label widget for instance:

BoxLayout:
    id: stubborn_layout
    size_hint_y: None
    height: lbl.height # Bind to Label height to update according to font size, for example

    TextInput:
        id: ti
        multiline: False
        #size_hint_y: None # The height of TextInput will depend on Label

    Label:
        id: lbl # Add id for referencing in stubborn_layout
        text: 'things'
        size_hint_x: None
        size_hint_y: None
        size: self.texture_size
        font_size: 12 # Try different font sizes. stubborn_layout will update accordingly
        padding_x: 6
        padding_y: 6

However a more elegant way would be to use a GridLayout and bind its minimum_height attribute to height. In this way, the parent layout would always update according to the height of the highest children.

GridLayout:
    id: stubborn_layout
    size_hint_y: None
    height: self.minimum_height # This does the trick of updating the height
    cols: 2 # If you want to add more children in horizontal layout, update the number of columns

    TextInput:
        id: ti
        multiline: False
        size_hint_y: None
        height: 300 # You can try different height values

    Label:
        text: 'things'
        size_hint_x: None
        size_hint_y: None
        size: self.texture_size
        font_size: 12 # Try different font_sizes
        padding_x: 6
        padding_y: 6

On a side note, do not use "" for id properties (https://kivy.org/docs/guide/lang.html#referencing-widgets)

Upvotes: 1

Related Questions