Phonon
Phonon

Reputation: 12737

Nesting layouts in Kivy placed contained widgets on bottom left

I'm probably missing something very basic, but I'm having a problem with object placement in Kivy when nesting layouts.

Suppose I do this:

<RootWidget>: # Derives from StackLayout

    orientation: 'tb-lr'
    size_hint: (None, 1)
    padding: (10, 10)
    spacing: (10, 10)

    Button:
        text: "One"
        size: 100, 100
        size_hint: None, None
    Button:
        text: "Two"
        size: 100, 100
        size_hint: None, None

This produces two buttons placed nicely inside the layout one above the other.

Now, if I nest on of the buttons inside yet another layout, like so:

<RootWidget>: # Derives from StackLayout

    orientation: 'tb-lr'
    size_hint: (None, 1)
    padding: (10, 10)
    spacing: (10, 10)

    Widget:
        size: 100, 100
        size_hint: None, None

        Button:
            text: "One"
            size: 100, 100
            size_hint: None, None

    Button:
        text: "Two"
        size: 100, 100
        size_hint: None, None

the first button ends up on the bottom left of the screen.

When I run Kivy inspector, it shows that Widget's position is correct, but the Button's position is 0,0 no matter what I do. I'm starting to suspect that it's got something to do with relative vs. absolute coordinates.

What's the right way to nest the first Button under something else while preserving its intended position?

P.S. I would really like to do this in the kv language rather than in Python, since I'm using a complicated template system, and this example is just a minimal example.

Upvotes: 1

Views: 3566

Answers (1)

Lobsterman
Lobsterman

Reputation: 256

Since widget does not automatically control the positioning and sizing of it's children you need to use a BoxLayout. Placing a widget in a BoxLayout automatically controls the positioning and size of the widget so that you won't get the widget being drawn at the default location and size -- at (x,y) = (0,0) and size (100, 100)

If the BoxLayout is horizontal, then adding another widget to the layout will push the previous widget over and resize them so that they both take up equal portions of the horizontal space.

You can then adjust the relative size of each widget by changing the size_hint attribute of the layout's children.

   Widget:
    size: 100, 100
    size_hint: None, None

    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: "One"
            size: 100, 100
            size_hint: None, None

Upvotes: 2

Related Questions