Ham789
Ham789

Reputation: 109

How to press and drag to select a group of ToggleButtons with Kivy?

I am hoping to implement some drag-select functionality to a grid of buttons in a GUI. I want to achieve something similar to a drag selection box on desktop operating systems. One press and drag should be able to toggle a group of toggle buttons of arbitrary size. Can I accomplish this with Kivy?

All I can seem to find is drag and drop functionality or multi-select of buttons by holding the shift key but not the exact functionality I am looking for.

Ideally the app could remember which group of toggle buttons were toggled by which specific drags by the user. Please see my attached image. Thank you in advance, any help is appreciated.

enter image description here

Here is my code so far: main.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.togglebutton import ToggleButton 

class ButtonGridLayout(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        for i in range(10 * 10):
            b = ToggleButton(text = str(i))
            self.add_widget(b)

class mainApp(App):
    pass

mainApp().run()

main.kv

ButtonGridLayout:
    rows: 10
    cols: 10

Upvotes: 2

Views: 116

Answers (1)

John Anderson
John Anderson

Reputation: 39012

That is a fairly complex coding exercise. But here are some hints to get you started.

  1. If you want to drag and drop Buttons in a Layout, you probably don't want to use GridLayout, as that Layout does its own positioning of its children. Something a bit more flexible, like a FloatLayout will likely work better.
  2. You can use on_touch_down(), on_touch_move(), and on_touch_up() methods in your Layout to draw and save a selection Rectangle.
  3. You can use the pos and size of the Buttons to compare to the Rectangle and determine which Buttons have been selected, and save them in a list.
  4. You can then use the same methods (as in hint #2) to drag and drop the list of selected Buttons
  5. You will need to distinguish selection touches from drag and drop touches from the basic Button touches, in the on_touch methods. The touch object has a button attribute that tells which mouse button was pressed and can be used for some of this. You may need to bind keyboard events so that you can require, for example, holding the ctrl button down while making the selection. And then, perhaps, require using the right mouse button to do the actual drag and drop.
  6. The drag and drop of a list of selected Buttons can be accomplished in an on_touch_move() method by just adding the touch.dpos to the pos of each selected Button.
  7. Also note that you cannot use pos_hint in the Buttons as that will over-ride any pos change that you make as a result of the dragging.

Upvotes: 2

Related Questions