Kivy在RecycleView中获取所有选中的项目

如何解决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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-