0

I was using kivymd MDList, but I have a problem.

My Code:

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

example_list = ['a', 'b', 'c']

KV = """
ScrollView:
    MDList:
        id: List
"""

ListItem = """
OneLineAvatarListItem:
    id: item
    text: ""
    ImageLeftWidget:
        source: "icon.png"
"""

class MainApp(MDApp):
    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        for letter in example_list:
            self.root.ids.item.text = letter
            self.root.ids.List.add_widget(Builder.load_string(ListItem))

MainApp().run()

I want to display List like this, But my code occurs this error:

 Traceback (most recent call last):
   File "kivy\properties.pyx", line 861, in kivy.properties.ObservableDict.__getattr__
 KeyError: 'item'

I think ListItem is not root, but I don't know how to solve this.

How can I change ListItem's text property?

Superjay
  • 447
  • 1
  • 7
  • 25

1 Answers1

2

Instead of loading the widget from a kv string, making it in python would be easier for this case, just create the MDList normally and in every iteration of the loop, create a new OneLineAvatarListItem Widget, set its properties, add the image, then add the whole widget to the MDList.

Code

from kivymd.app import MDApp
from kivymd.uix.list import OneLineAvatarListItem, ImageLeftWidget
from kivy.lang.builder import Builder

example_list = ['a', 'b', 'c']

KV = """
ScrollView:
    MDList:
        id: List
"""

class MainApp(MDApp):
    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        global example_list
        for letter in example_list:
            one_line = OneLineAvatarListItem(text = letter)
            image = ImageLeftWidget(source = "icon.png")
            one_line.add_widget(image)
            self.root.ids.List.add_widget(one_line)

MainApp().run()
Yash Kolekar
  • 270
  • 1
  • 11
  • Thank you! But my last question: in PyCharm, it works well but it shows warning `Unexpected argument` on `source = "icon.png"`. Do you know why? Thanks! – Superjay Jan 09 '21 at 07:41
  • @JayLee probably because the __init__ does not have a source argument, try doing this `image = ImageLeftWidget()` then on next line `image.source = "icon.png"` – Yash Kolekar Jan 09 '21 at 07:43
  • @JayLee happy to help :) – Yash Kolekar Jan 09 '21 at 07:49