Search code examples
kivyalignmentandroid-relativelayout

KIVY Custom Widget pos_hint


While using Custom widget only 'x' and 'y' parameters are evaluated in pos_hint parameter. But if I use other keys like center_x, center_y or top the key values are not evaluated. In sample program given below, if I use pos_hint as center_x and center_y the line is not aligned in middle of the layout. But if i Use x and y parameter alignment works.

from kivy.app import App
from kivy.graphics import Line
from kivy.uix.scatter import Scatter
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.scatterlayout import ScatterLayout


class MyPaintWidget(Scatter):

    def __init__(self, **kwargs) :
        super(MyPaintWidget, self).__init__(**kwargs)

    def create_figure(self,  **kwargs):
        self.canvas.add(Line( points=[0, 10, 30, 10]))
        return self

class MyPaintApp(App):

    def build(self):
        parent = RelativeLayout()

        #self.painter = MyPaintWidget(pos_hint={'center_x': 0.5, 'center_y':0.5}) Not working with center_x and center_y alignment
        self.painter = MyPaintWidget(pos_hint={'x': 0.5, 'y':0.5}) #working with x and y parameter

        parent.add_widget(self.painter.create_figure())

        return parent

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

Even tried with sample KV file as mentioned in comments section

from kivy.app import App
from kivy.graphics import Line
from kivy.uix.scatter import Scatter
from kivy.uix.relativelayout import RelativeLayout
from kivy.lang import Builder

KV = '''
<LineRectangle>:
    canvas:
        Color:
            rgba: .1, .1, 1, .9
        Line:
            width: 2.
            rectangle: (self.x, self.y, self.width, self.height)
    Label:
        center: root.center
        text: 'Rectangle'
'''

class LineRectangle(Scatter):
      pass

class MyPaintApp(App):

    def build(self):
        Builder.load_string(KV)
        root = RelativeLayout()
        #root.add_widget(LineRectangle(pos_hint={'center_x':0.5, 'center_y':0.5}, size_hint=(0.2, 0.2)))
        root.add_widget(LineRectangle(pos_hint={'center_x':0.5, 'center_y':0.5}, size_hint=(None, None)))
        return root

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

Solution

  • pos_hint property allows you to set the position of the widget inside its parent layout, in percent (similar to size_hint).