pythonkivymodal-view

Doing a ModalView subclass in Kivy messes up position of view and children


I have a very simplistic case of a window with a single button. With a button release I want to pop up a modal view with some text on it. In every button release I create and open an instance of ModalView and it works:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.modalview import ModalView
from kivy.uix.label import Label

class AButton(Button):
    def on_release(self, *largs):
        view = ModalView(size_hint=(None, None), size=[200, 200])
        view.add_widget(Label(text='I am a modal view'))
        view.open()


class MyApp(App):
    def build(self):
        return AButton()


if __name__ == '__main__':
    MyApp().run()

Now let's say I want to create a subclass of ModalView so I don't have to specify size_hint and size every time I pop up a modal view. This is the code after that change:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.modalview import ModalView
from kivy.uix.label import Label
from kivy.properties import ListProperty

class AButton(Button):
    def on_release(self, *largs):
        view = ModalView2()
        view.add_widget(Label(text='I am a modal view'))
        view.open()


class ModalView2(ModalView):
    size_hint = ListProperty([None, None])
    size = ListProperty([200, 200])

    def __init__(self, **kwargs):
        super(ModalView2, self).__init__(**kwargs)


class MyApp(App):
    def build(self):
        return AButton()


if __name__ == '__main__':
    MyApp().run()

ModalView and Label position get totally messed up. I tried with anchor_x and anchor_y in ModalView2 in an attempt to fix the label position with no luck. What am I doing wrong?


Solution

  • The ModalView already has size_hint and size attributes, so you don't need to create new ones, just set the existing attributes to the values you want:

    class ModalView2(ModalView):
    
        def __init__(self, **kwargs):
            super(ModalView2, self).__init__(**kwargs)
            self.size_hint = (None, None)
            self.size = (200, 200)