Adaptive_width property of MDLabel is not working correctly

Viewed 163

I am making an app using kivy & kivymd and in one part of it, I would like the labels to take as much space as the actual text.

This seems pretty straightforward with kivy itself but for some reason, nothing works with the MDLabel class. I tried setting the adaptive_width property to True and I also tried to directly set the width to the texture_size[0] property but none of them worked (and yes I installed kivymd directly from github).

Here is my code:

from kivy.lang import Builder
from kivymd.app import MDApp


class MainApp(MDApp):
    def __init__(self, **kwargs):
        super(MainApp, self).__init__(**kwargs)
        self.kv = Builder.load_string('''
#:kivy 2.0.0
BoxLayout:
    MDLabel:
        text: "Supposedly adaptive width (KivyMD)"
        font_size: "21sp"
        halign: "center"
        adaptive_width: True
        # I also tried directly setting the width to the texture_size but the results were worse
        # size_hint_x: None
        # width: self.texture_size[0]
        canvas.before:
            Color:
                rgba: .8, .1, .2, .5
            Rectangle:
                pos: self.pos
                size: self.size
    Widget:
    MDSeparator:
        orientation: "vertical"
    Widget:
    Label:
        text: "Actual adaptive width (Standard Kivy)"
        font_size: "21sp"
        color: 0, 0, 0, 1
        size_hint_x: None
        width: self.texture_size[0]
        canvas.before:
            Color:
                rgba: 0, .6, .2, .5
            Rectangle:
                pos: self.pos
                size: self.size
''')

    def build(self):
        return self.kv


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

Here is my results: my results

1 Answers

I don't believe that MDLabel supports the adaptive_width property. In using the width: self.texture_size[0], it seems that you must also add the text_size: None, None to the MDLabel, and it seems that its location in the kv is important. Here is a version of part of your kv that seems to work:

BoxLayout:
    MDLabel:
        text: "Supposedly adaptive width (KivyMD)"
        font_size: "21sp"
        halign: "center"
        # adaptive_width: True
        # I also tried directly setting the width to the texture_size but the results were worse
        size_hint_x: None
        width: self.texture_size[0]
        text_size: None, None  # added, and must be in this location
        canvas.before:
            Color:
                rgba: .8, .1, .2, .5
            Rectangle:
                pos: self.pos
                size: self.size
Related