Wednesday, May 28, 2014

8. GridLayout

GridLayout lays out the widgets as a matrix.




It is similar to the StackLayout orientation of left-to-right, and top-to-bottom. Either, we set rows, or cols, which stands for columns, and the layout knows that, this number is, the maximum number of widgets, in a given row or column, depending on which parameter is given.




In this kv file, we set cols to be 3. There are nine buttons, and since, none have an explicit size_hint, all will be the same size, and a matrix of 3 by 3 is created.




The main Python file is shown. It imports the gridlayout module as the alias TheGrid. This is not the standard way of doing things in Kivy, as now to access the class GridLayout, we have to write TheGrid.GridLayout. This is a confusing way of doing things and not recommended.


# mygrid.py

import kivy.uix.gridlayout as TheGrid
from kivy.app import App

class MyGrid(TheGrid.GridLayout):
    pass
   
class MyGridApp(App):
    def build(self):
        return MyGrid()

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




This is the result, showing the buttons in a 3 by 3 matrix. We can also, put rows at 3, in the Kivy file, and the result will be the same.




Each widget in GridLayout has a size_hint of 1,1 . Thus, to change the width and height, we have to give a scaling factor.




In this kv file, only the Button 'B3' has an explicit size_hint, which is 2,2. Thus, this Buttons is twice the width and height as the other buttons. This is only true, in reference to buttons, not in the row or column of the widget, with the new scaling. All widgets in the same row, will get the same height, and all widgets in the same column will get the same width.


# mygrid.kv

<MyGrid>:
    cols: 3
    spacing: 20
    padding: [20,10]
    Button:
        text: 'B1'
    Button:
        text: 'B2'
    Button:
        text: 'B3'
        size_hint: [2,2]
    Button:
        text: 'B4'
    Button:
        text: 'B5'
    Button:
        text: 'B6'
    Button:
        text: 'B7'
    Button:
        text: 'B8'
    Button:
        text: 'B9'



In this result, we can see that even though, we explicitly only changed B3, we can see how it also effects the row and column, which is scaled.




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