gilgamash
gilgamash

Reputation: 902

Kivy access gridlayout within scrollview dynamically in python

I am trying to add labels/buttons to a GridLayout within a Scrollview, but somehow I cannot access the GridLayout in python. Consider the following .kv section

<DrvList>
    ScrollView:
        size_hint: (None, None)
        size: 0.95, 0.95
        GridLayout:
            minimum_height: self.height
            id: grid
            size_hint_y: None
            rows: 3
            cols: 1

and a simplified respective Python section

class DrvList(ScrollView):
    selection = StringProperty()

    def __init__(self, *args, **kwargs):
        super(DrvList, self).__init__(*args, **kwargs)
        self._src = ["C", "D", "E"]
        for x in self._src:
            self.grid.add_widget(ToggleButton(id=x, text=x))
        DrvList.selection = self._src[0]

I get an error

 AttributeError: 'DrvList' object has no attribute 'grid'

so how can I access the Grid? Also, any suggestions on making such a list "drag and droppable" such that I can move around items in the list with visual feedback? But most important for now the issue of how ti access the grid. self.ids.grid does not work, either...

EDIT: Kivy >= 1.11.x, so not 1.10 or below

Upvotes: 0

Views: 118

Answers (1)

John Anderson
John Anderson

Reputation: 38822

A few issues with your code. First is that the ids are created when the kv rules are applied, and I must admit that when those ids are actually available seems difficult to define. However, typically when ids are unavailable, that can be overcome by using Clock.schedule_once() like this:

class DrvList(ScrollView):
    selection = StringProperty()

    def __init__(self, *args, **kwargs):
        super(DrvList, self).__init__(*args, **kwargs)
        Clock.schedule_once(self.setup)

    def setup(self, dt):
        self._src = ["C", "D", "E"]
        for x in self._src:
            self.ids.grid.add_widget(ToggleButton(id=x, text=x))
        self.selection = self._src[0]   # Properties should be referenced using "self"

Also, note that in your kv, the lines:

    size_hint: (None, None)
    size: 0.95, 0.95

are setting the ScrollView size to less than 1 pixel by 1 pixel, so it will likely not be visible.

One other note is that your kv puts a ScrollView inside DrvList, but DrvList is a ScrollView, so you are placing a ScrollView inside a ScrollView, which may cause difficulties when you try to actually scroll.

Upvotes: 1

Related Questions