如何解决Kivy在RecycleView中获取所有选中的项目
问题
我一直在弄乱Kivy的RecycleViews,希望为我的一个项目创建list builder。我正在研究Kivy文档的RecycleView页面上的第二个示例,因为它已经几乎是我要创建的内容。作为参考,该示例包含一个列表,其中可以选择或取消选择多个项目。
我的主要问题是我无法找到任何方法来获取包含RecycleView中所有选定项目的列表。我至少认为,我可以使用apply_selection()
类中的SelectableLabel
方法在RecycleView中有一个单独的列表,其中包含所有选中的项,但是我无法区分取消选择{{1 }},将标签移到RecycleView的视图之外。
代码
listBuilder.py
SelectableLabel
listBuilder.kv
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.datamodel import RecycleDataModel
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
class TestScreen(Screen):
''' Screen for testing stuff '''
def pressed(self):
print(f'Selected: {self.ids.rv.data}')
self.ids.rv.data.append({'text': '200'})
class RV(RecycleView):
''' Recycle View '''
def __init__(self,**kwargs):
super(RV,self).__init__(**kwargs)
self.data = [{'text': str(x)} for x in range(100)]
class SelectableRecycleBoxLayout(FocusBehavior,LayoutSelectionBehavior,RecycleBoxLayout,RecycleDataModel):
''' Adds selection and focus behaviour to the view. '''
def on_data_changed(self,**kwargs):
print('Data changed: ',kwargs)
super(SelectableRecycleBoxLayout,self).on_data_changed(**kwargs)
class SelectableLabel(RecycleDataViewBehavior,Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self,rv,index,data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableLabel,self).refresh_view_attrs(
rv,data)
def on_touch_down(self,touch):
''' Add selection on touch down '''
if super(SelectableLabel,self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index,touch)
def apply_selection(self,is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
if is_selected:
print("selection changed to {0}".format(rv.data[index]))
else:
print("selection removed for {0}".format(rv.data[index]))
Builder.load_file('listBuilder.kv')
class MainApp(App):
def build(self):
return TestScreen()
if __name__ == '__main__':
MainApp().run()
对于想知道为什么在此示例中使用屏幕的人来说,这是因为这是使用屏幕的大型程序的测试代码。
我正在使用Kivy 1.11.1和Python 3.7.8
感谢您的帮助,因为我不太了解,但尚未完全掌握RecycleView数据模型。
谢谢!
解决方法
如果将selected
添加为RecycleView
数据中的键,那么您将获得所需的内容:
class RV(RecycleView):
''' Recycle View '''
def __init__(self,**kwargs):
super(RV,self).__init__(**kwargs)
self.data = [{'text': str(x),'selected': False} for x in range(100)]
然后,在SelectableLabel
类中:
def apply_selection(self,rv,index,is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
# change selected in data
rv.data[index]['selected'] = self.selected
if is_selected:
print("selection changed to {0}".format(rv.data[index]))
else:
print("selection removed for {0}".format(rv.data[index]))
最后,您可以在pressed()
方法中汇编列表:
def pressed(self):
print('Selected:')
rv = self.ids.rv
for d in rv.data:
if d['selected']:
print('\t',d)
,
当我开始更深入地研究我的项目并认为我会在这里分享它时,我找到了另一个解决方案。
有一个内置的方法来获取选定的节点;它是通过RecycleView.layout_manger.selected_nodes
访问的。它返回一个索引选定节点的列表,尽管应该注意的是它们不是按数字顺序而是按照选择节点的顺序。
这是我使用新方法对原始代码所做的更改:
RV舱:
class RV(RecycleView):
''' Recycle View '''
def __init__(self,self).__init__(**kwargs)
self.data = [{'text': str(x)} for x in range(100)]
def get_selected(self):
''' Returns list of selected nodes dicts '''
return [self.data[idx] for idx in self.layout_manager.selected_nodes]
如果您只关心索引,则不一定需要一种方法,但是我认为获取实际的字典会很好。
然后按下的方法如下:
def pressed(self):
print('Selected:')
for d in self.ids.rv.get_selected():
('\t',d)
我选择切换到此方法的主要原因是selected
字典键与节点的选定状态不对应。在程序中,我必须从列表中删除某些项目,然后选择旧索引处的新项目。有点奇怪,但是在将选择视为索引列表而不是是否选择单个项目时,这更有意义。
对于那些在删除原始列表后选择其他列表项时遇到麻烦的人,我发现这很有帮助:https://www.reddit.com/r/kivy/comments/6b0pfp/dhjh7q4
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。