techhighlands
techhighlands

Reputation: 972

Kivy Rectangle not getting sized properly

When drawing a rectangle in the canvas of a widget, the size_hint seems to have no effect. I expected the rectangle to have the following sizes:

But, no matter what, the rectangle's size is fixed at the default 100 by 100.

Any ideas how to apply sizing to the rectangle based on the layout's size?

Using kv language is not an option. I am looking for a pure Python solution.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.graphics import Color, Rectangle


class RootWidget(BoxLayout):
    pass


class GomokuLayout(FloatLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        with self.canvas.before:
            Color(0, 0, 255, 1)
            self.rect = Rectangle(size=self.size, pos=self.pos)

        self.bind(size=self._update_rect, pos=self._update_rect)

    def _update_rect(self, instance, value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size


class GridView(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        with self.canvas:
            Color(1, 0, 0, 1)
            Rectangle(size_hint=(0.1, 0.5))


class GomokuApp(App):
    def build(self):
        root = RootWidget()
        gomoku_layout = GomokuLayout()
        root.add_widget(gomoku_layout)
        gomoku_layout.add_widget(GridView())

        return root


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

Upvotes: 1

Views: 337

Answers (1)

CrazyChucky
CrazyChucky

Reputation: 3518

Rectangle takes size, not size_hint. Drawing objects in a canvas works a little differently than sizing/positioning widgets.

Upvotes: 1

Related Questions