Monday, June 2, 2014

12. FloatLayout


FloatLayout is very similar to RelativeLayout, except, if position is given, it is relative to the root window.




Thus in FloatLayout, you are not confined to the layout, but can have children anywhere in the window. Thus, position of 0,0 always refers to lower-left corner.




The Python program uses GridLayout for the root widget which is defined in the kv file.


# ex12.py

from kivy.uix.gridlayout import GridLayout
from kivy.app import App

class Ex12(GridLayout):
    pass
   
class Ex12App(App):
    def build(self):
        return Ex12()

if __name__=='__main__':
    Ex12App().run()



In the first part of the kv file, a new class is created. MyButton is based on the Button class, but has a size of 100 pixels by 100 pixels.




There are 2 columns in the Grid Layout. Since we will have 2 children, both will take half of the space horizontally, as their size is not explicitly set. Alternatively, we can have used BoxLayout and obtained the same results. For the root widget, we define canvas instructions so the first half of the window is green, and the next half is blue. Note, root.size contains x and y components corresponding to the root window.




Here the two childs are defined. The first is RelativeLayout, with a button 'B1' at 0,0. This is the lower-left corner of the layout as well as the root window. The next child is FloatLayout, and buttons 'B2a' and 'B2b' are defined. The button 'B2a', is just next to 'B1', and 'B2b' is just near the half-way point in x-direction and 100 pixels up in the y-direction.


# ex12.kv

<MyButton@Button>:
    size_hint: None, None
    size: 100, 100
  
<Ex12>:
    cols: 2
    canvas:
        Color:
            rgb: 0,1,0
        Rectangle:
            pos: 0,0
            size: root.size[0]/2,root.size[1]
        Color:
            rgb: 0,0,1
        Rectangle:
            pos: root.size[0]/2,0
            size: root.size[0]/2,root.size[1]
    FloatLayout:
        MyButton:
            text: 'B1'
            pos: 0,0
    RelativeLayout:
        MyButton:
            text: 'B2a'
            pos: 100,0
        MyButton:
            text: 'B2b'
            pos: root.size[0]/2-100,100



This is the result of the layout. We see that 'B2a' and 'B2b' are not actually inside the Float Layout.




The kv file is changed so FloatLayout is first and RelativeLayout is second. Since 'B2a' and 'B2b' coordinates are now relative, the positions are inside the second half.




With this result, we can see the buttons 'B2a' and 'B2b' are now in the second layout.




2 comments:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Python Training in electronic city

    ReplyDelete