2023-07-01

Convert .kv to custom python class

I'm new to Kivy and having a hard time understanding why my code isn't working.

I'd like to convert some reusable Kv language code into a custom python class but I can't figure out why it's not working.

<ReceivingShipmentDetailScreen>:
    BoxLayout:
        orientation: 'vertical'
        padding: 20
        spacing: 15

        BoxLayout:
            size_hint_y: None
            height: 50

            canvas.before:
                Color:
                    rgba: (0.1803921568627451, 0.20784313725490197, 0.24313725490196078, 1)
                Rectangle:
                    pos: self.pos
                    size: self.size

            Label:
                text: 'Receive New Shipment'
                bold: True
                font_size: 20

I attempted to create a python class and pass in page_header_text when it's called in my Kv code but it doesn't seem to be working.

The text reads "Title" instead of the expected "Receive New Shipment". Also the format is messed up; the label and rectangle are in separate parts of the page. It seems that CustomLayout also doesn't have a parent widget and the size is different than expected.

class CustomLayout(BoxLayout):
    page_header_text = StringProperty('Title')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        self.padding = 20
        self.spacing = 15

        page_header = BoxLayout(
            size_hint_y=None,
            height=50,
        )
        with page_header.canvas.before:
            Color(
                0.1803921568627451,
                0.20784313725490197,
                0.24313725490196078,
                1,
            )
            Rectangle(pos=page_header.pos, size=page_header.size)

        page_header.add_widget(Label(
            text=self.page_header_text,
            bold=True,
            font_size=20,
        ))

        self.add_widget(page_header)

Here's my usage the usage in the .kv file.

<ReceivingShipmentDetailScreen>:
    CustomLayout:
        page_header_text: 'Receive New Shipment'

What am I missing here?



No comments:

Post a Comment