Question

I'm trying to make a gridview with square elements inside of it that scrolls. I found some code in the documentation and some on the internet and I managed to get something working.

class ElementPage(Screen):
    def __init__(self, **kwargs):
        layout = GridLayout(cols=3, spacing=10, size_hint_y=None)
        layout.bind(minimum_height=layout.setter('height'))
        for i in range(100):
            icon = ElementIcon(str(i), "cat.png", size_hint_y=None)
            icon.height = icon.width
            layout.add_widget(icon)
        scrollview = ScrollView(size_hint=(None, None), size=(400, 400), pos_hint={'center_x': .5, 'center_y': .5})
        scrollview.add_widget(layout)
        super().__init__(**kwargs)
        self.add_widget(scrollview)

Running this I get a scrolling grid of ElementIcon that I can scroll, but its always 400x400 pixels in size, regardless of window size. Is there a way to make it the size of the window (actually, the parent widget), or better yet is there a way to set what percentage of the size I want it to be?

I tried messing with the code, especially this line:

scrollview = ScrollView(size_hint=(None, None), size=(400, 400), pos_hint={'center_x': .5, 'center_y': .5})

But with no luck.

Was it helpful?

Solution

Works for me as long as you don't specify any sizing for the ScrollView.

Change this:

scrollview = ScrollView(size_hint=(None, None), size=(400, 400), pos_hint={'center_x': .5, 'center_y': .5})

...to this:

scrollview = ScrollView()

To keep the buttons square, we can use GridLayout's row_default_height:

layout = GridLayout(cols=3, spacing=10, size_hint_y=None, row_force_default=True)
layout.bind(width=lambda *_: setattr(layout, 'row_default_height', 
        (layout.width - (layout.spacing[0] * (layout.cols - 1))) / layout.cols))
layout.bind(minimum_height=layout.setter('height'))

OTHER TIPS

You might try changing:

size=(400,400)

to

size=(min(root.width, root.height),min(root.width, root.height))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top