How To Select Multiple Images In Checkbox In Recycle View Kivy?
Solution 1:
If you are using MDCheckbox
in a RecycleView
, then you should include the state
of that MDCheckbox
in the data
. If you don't do that, then the RecyclView
doesn't know about the state
of the MDCheckbox
and when an MDCheckbox
gets recycled, its state
will be whatever it was last time it was used.
To accomplish that, first modify your kv
rule for ImgCard
:
<ImgCard@BoxLayout>path:""selected:False# added to indicate selectionindex:-1# added to enable accessing this item in the dataorientation:"vertical"size_hint_y:NoneImage:source:root.pathsize_hint_y:.9MDCheckbox:id:cbstate:'down'ifroot.selectedelse'normal'on_release:app.root.adjust_data(root)
Note that the ButtonBehavior
is not necessary.
Then, modify the initial data
to initialize the new properties:
defload_images(self):
count = 0ifnot self.manager_list:
for image in os.listdir(self.dir):
target_filename, target_file_extension = os.path.splitext(image)
if target_file_extension in self.available_image_format:
path_to_image = os.path.join(self.dir, image)
self.manager_list.append(
{
"ImgCard": "ImageManager",
"path": path_to_image,
"height": dp(200),
"selected": False,
"index": count
}
)
count += 1
self.ids.img_base.data = self.manager_list
self.images = [self.dir]
And add a method in the Gallery
class to update the data
when a MDCheckbox
is changed:
defadjust_data(self, imgcard):
rv = self.ids.img_base
rv.data[imgcard.index]['selected'] = imgcard.ids.cb.state == 'down'
imgcard.ids.cb.state = 'normal'
rv.refresh_from_data()
To remove the selected items, you can add a Button
in your <Gallery>
rule that calls:
defdelete(self, instance):
rv = self.ids.img_base
deleted = Falsefor i inrange(len(rv.data) - 1, -1, -1):
item = rv.data[i]
if item['selected']:
del rv.data[i]
deleted = Trueif deleted:
self.adjust_indices()
Since deleting any items will upset the index
property of items in the data
, another method is required to adjust the index
properties:
defadjust_indices(self):
# adjust index values to account for removd items
rv = self.ids.img_base
index = 0for item in rv.data:
item['index'] = index
index += 1
Post a Comment for "How To Select Multiple Images In Checkbox In Recycle View Kivy?"