Search code examples
pythonkivy

How show details of an item when recycleview button is clicked in Kivy


I have items in database that have id, name, description, image. I am pulling it and displaying the name as button using Recycleview in Kicy

class ItemsView(RecycleView):

    def __init__(self, **kwargs):
        super(ItemsView, self).__init__(**kwargs)
        self.load_data()


    def load_data(self, *args):

    
        c = mydb.cursor()

        c.execute("SELECT id, name, description FROM items")

        list_data = []
        for item in c:
            list_data.append({'text': item[1], 'id': item[0], 'desc': item[2]})

In .kv file

<ItemsView>:
    viewclass: 'Button'
    RecycleBoxLayout:
        color: 1,1,1,1
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'

So far I have the names as button. When I click on that button, I want to display a new screen which shows that particular items description and image. How can I achieve that?


Solution

  • In the data of the RecycleView, you can specify any property of the viewclass. Since your viewclass is a Button, you can add on_release to the data. Something like this:

        for item in c:
            list_data.append({'text': item[1], 'id': item[0], 'desc': item[2], 'on_release': partial(self.doit, item)})
    

    The above arranges for each of the Buttons to call a doit() method of your ItemsView class with an argument of the item.

    Then you can add the doit() method to the ItemsView() class:

    def doit(self, item):
        print('in doit:', item)
    

    Obviously, you can do anything you want inside the doit() method.