Search code examples
pythonandroidlistviewkivyscrollview

KivyMD Scrollview Example


I was able to find this example of kivymd handling scrollview with MDlist. I am struggling to make it run.

The I am not familiar with the error code i am receiving and I was unsuccessful finding any help so far .

Here is the code :

from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from kivymd.app import MDApp

kv =""""
<scrollview>
    ScrollView:
            do_scroll_x: False  # Important for MD compliance
            MDList:
                OneLineListItem:
                    text: "Single-line item"
                TwoLineListItem:
                    text: "Two-line item"
                    secondary_text: "Secondary text here"
                ThreeLineListItem:
                    text: "Three-line item"
                    secondary_text: "This is a multi-line label where you can fit more text than usual"
"""
class MainApp(MDApp):
    def build(self):
        self.root_widget = Builder.load_string(kv)
        sv = ScrollView()
        ml = MDList()
        sv.add_widget(ml)
        contacts = ["Paula", "John", "Kate", "Vlad"]
        for c in contacts:
            ml.add_widget(
                OneLineListItem(
                    text=c
                )
            )
        return self.root_widget

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

Please Help !


Solution

  • I don't understand your kv string. First, the opening and ending quotes should match (you start with 4 and end with 3). Second, you have a <scrollview> entry. I don't think that is a legal entry. And third, the rest of your kv string has inconsistent indentation. It looks like your kv string is trying to create a ScrollView containing an MDList. If that works, then your call to ScrollView in the build() method will create such a ScrollView containing an MDList. Then the line sv.add_widget(ml) will try to add a second MDList to the ScrollView (which should produce an error, since only one child is allowed in a ScrollView). Then the build() method is returning self.root_widget which is unrelated to the sv that you have just created.

    So here is a modified version of your code that uses the sv that you create in your build() method:

    from kivy.uix.scrollview import ScrollView
    from kivymd.app import MDApp
    from kivymd.uix.list import MDList, OneLineListItem
    
    
    class MainApp(MDApp):
        def build(self):
            sv = ScrollView()
            ml = MDList()
            sv.add_widget(ml)
            contacts = ["Paula", "John", "Kate", "Vlad"]
            for c in contacts:
                ml.add_widget(
                    OneLineListItem(
                        text=c
                    )
                )
            return sv
    
    if __name__ == '__main__':
        MainApp().run()
    

    If you add enough names to the contacts list, the scrolling will work.