jeudi 30 septembre 2021

Kivymd: How to add checkbox in List item without creating custom class?

How can I add checkbox with MDList item? In my project I need an event as like, 'Store selected items texts in a python list after clicking a button.' It can be done easily when I create a custom class for List with checkbox (As shown in kivymd documentation).

from kivy.lang import Builder

from kivy.properties import StringProperty
from kivymd.app import MDApp
from kivymd.uix.list import IRightBodyTouch, TwoLineAvatarIconListItem
from kivymd.uix.selectioncontrol import MDCheckbox

KV = """
<ListItemWithCheckbox>:
    IconLeftWidget:
        icon: root.icon
    RightCheckbox:
        id: cb

BoxLayout:

    ScrollView:

        MDList:
            id: scroll
            
    MDRaisedButton:
        text: "Save"
        on_release: app.save_checked()
"""

class ListItemWithCheckbox(TwoLineAvatarIconListItem):
    """Custom list item."""
    icon = StringProperty("android")

class RightCheckbox(IRightBodyTouch, MDCheckbox):
    """Custom right container."""

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

    def on_start(self):
        for i in range(15):
            self.root.ids.scroll.add_widget(
                ListItemWithCheckbox(text=f"Item {i}", secondary_text=f"Item {i+10}", icon='User_images/s.jpg')
            )
    def save_checked(self):
        mdlist = self.root.ids.scroll  # get reference to the MDList
        selected_item = []
        for wid in mdlist.children:
            if isinstance(wid, ListItemWithCheckbox):  # only interested in the ListItemWithCheckboxes
                cb = wid.ids.cb  # use the id defined in kv
                if cb.active:  # only append selected items

                    selected_item.append(wid.text)
        selected_item = selected_item[::-1]
        print(selected_item)


MainApp().run()

When I try to apply this thing with screen manager(for handling multiple screen) it is not working. Can I create a list with checkbox without creating custom class for list?

NB: My requirement is, I need a list with checkbox. After selecting list item when press a button the selected item should print (or used in other purpose)




Aucun commentaire:

Enregistrer un commentaire