Mseddi Said
Mseddi Said

Reputation: 21

How can I detect selected checkbox with kivy

Thanks to this code, I can create interface to present a List of information. However, I need to create a function when I click the button "save" I print all text item selected in CheckBox

from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.list import ILeftBodyTouch, TwoLineAvatarIconListItem
from kivymd.uix.selectioncontrol import MDCheckbox


KV = """
<ListItemWithCheckbox>:

    RightCheckbox:


BoxLayout:

    ScrollView:

        MDList:
            id: scroll
            
    MDRaisedButton:
        text: "Save"
"""


class ListItemWithCheckbox(TwoLineAvatarIconListItem):
    """Custom list item."""



class RightCheckbox(ILeftBodyTouch, 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}")
            )


MainApp().run()

Upvotes: 0

Views: 408

Answers (1)

John Anderson
John Anderson

Reputation: 38992

You can do that by defining a method in your App:

def save_checked(self):
    mdlist = self.root.ids.scroll  # get reference to the MDList
    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 print selected items
                print(wid.text, wid.secondary_text)

Then modify kv to call that method on Button release:

MDRaisedButton:
    text: "Save"
    on_release: app.save_checked()

and add the id for the RightCheckbox in the kv:

<ListItemWithCheckbox>:

    RightCheckbox:
        id: cb

Upvotes: 1

Related Questions