Search code examples
pythonlistkivyscrollview

Centering MDlist Text under ScrollView KivyMD


I am struggling to center the text in ScrollView.

My KV code is the following :

from kivy.uix.scrollview import ScrollView
from kivymd.app import MDApp
from kivymd.uix.list import MDList, OneLineListItem

kv =""""
    ScrollView:
        do_scroll_x: False  # Important for MD compliance
        MDList:
            OneLineListItem:
                text: "Single-line item"
"""

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()

This is what the screen looks like : Centering Issue

Please help!


Solution

  • One way to do it, is to subclass the OneLineListItem, so you can add a halign argument for horizontal alignment:

    class OneLineListItemAligned(OneLineListItem):
        def __init__(self, halign, **kwargs):
            super(OneLineListItemAligned, self).__init__(**kwargs)
            self.ids._lbl_primary.halign = halign
    
    
    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(OneLineListItemAligned(halign="center", text=c))
            return sv
    
    if __name__ == '__main__':
        MainApp().run()
    

    P.S. The kv part of the code is not used in your example...