Issue
This Content is from Stack Overflow. Question asked by Ham789
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. 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 toggle buttons were toggled by which specific drags by the user. Please see my attached image. Thank you in advance, any help is appreciated.
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
Solution
That is a fairly complex coding exercise. But here are some hints to get you started.
- If you want to drag and drop
Buttons
in aLayout
, you probably don’t want to useGridLayout
, as thatLayout
does its own positioning of its children. Something a bit more flexible, like aFloatLayout
will likely work better. - You can use
on_touch_down()
,on_touch_move()
, andon_touch_up()
methods in yourLayout
to draw and save a selectionRectangle
. - You can use the
pos
andsize
of theButtons
to compare to theRectangle
and determine whichButtons
have been selected, and save them in a list. - You can then use the same methods (as in hint #2) to drag and drop the list of selected
Buttons
- You will need to distinguish selection touches from drag and drop touches from the basic
Button
touches, in theon_touch
methods. Thetouch
object has abutton
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 thectrl
button down while making the selection. And then, perhaps, require using the right mouse button to do the actual drag and drop. - The drag and drop of a list of selected
Buttons
can be accomplished in anon_touch_move()
method by just adding thetouch.dpos
to thepos
of each selectedButton
. - Also note that you cannot use
pos_hint
in theButtons
as that will over-ride anypos
change that you make as a result of the dragging.
This Question was asked in StackOverflow by Ham789 and Answered by John Anderson It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.