Search code examples
kivypopupdraggable

draggable popup widget of kivy


I'm trying to make a draggable popup use kivy,i have tried several methods, for instance on_touch_move, dragbehavior. but all of it can't work,so does anybody master can offer some ideas?

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.uix.behaviors import DragBehavior


class DraggableLayout(DragBehavior, FloatLayout):
    pass


class DraggablePopup(Popup):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.content = DraggableLayout()


class DraggablePopupApp(App):
    def build(self):
        # Create a DraggablePopup instance
        popup = DraggablePopup(size_hint=(None, None), size=(400, 400))

        return popup


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

Solution

  • You are attaching the DragBehavior to the content of the Popup rather than the Popup. Try changing:

    class DraggablePopup(Popup):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            self.content = DraggableLayout()
    

    to:

    class DraggablePopup(DragBehavior, Popup):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            self.content = DraggableLayout()
    
        def _align_center(self, *_args):
            pass
    

    The _align_center() method overrides the same method in ModalView, which keeps the ModalView centered in your window. Overriding this method so that it does nothing allows the Popup to be dragged.

    There are also some properties that the DragBehavior requires, and these can be set by adding:

    Builder.load_string('''
    <DraggablePopup>:
        # Define the properties for the DraggablePopup
        drag_rectangle: self.x, self.y, self.width, self.height
        drag_timeout: 10000000
        drag_distance: 0
    ''')
    

    in your python code.