python Kivy MD:如何从uix.list / OneLineAvatarIconListItem中获取选定的项目

ruoxqz4g  于 2023-03-06  发布在  Python
关注(0)|答案(1)|浏览(115)

我是Kivy的新手,我用Python/KivyMD开发了一个简单的UI,它显示了一个项目列表:每个列表都有一个复选框,允许用户选择该项目。2显示该列表的对象是从 kivymd.uix.list 继承而来的。3我想得到该列表的选定项目。4下面是代码:

from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.list import IRightBodyTouch, OneLineAvatarIconListItem
from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.toast import toast
import numpy as np

Builder.load_string(
    """    
<ListItemWithCheckbox>:
    RightCheckbox:
       
<View>:
    MDScrollView:
        MDList:
            id: scroll                
"""
)
    
    
class ListItemWithCheckbox(OneLineAvatarIconListItem):
    pass

class RightCheckbox(IRightBodyTouch, MDCheckbox):
    pass

    

class View(MDFloatLayout): 
    detectedDevices = list()
    for i in range(20):
        device = dict(name='DEVICE ' + str(i), index=i+1, battery_level=np.random.randint(low=0, high=101))
        detectedDevices.append(device)
    
    
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        for i in range(len(self.detectedDevices)):
            self.ids.scroll.add_widget(ListItemWithCheckbox(text=self.detectedDevices[i]['name']))
    
    
  
class MainApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.view = View()
        

    def build(self):
        self.title = ''
        return self.view
  

if __name__ == '__main__':
    MainApp().run()
kgsdhlau

kgsdhlau1#

您可以使用MDCheckboxon_state方法维护选定项的列表,以便每当选定项时触发该列表的更新。
下面是一种方法。首先,向MDCheckBox添加一个id

<ListItemWithCheckbox>:
    RightCheckbox:
        id: check

然后修改RightCheckbox类,以便在任何RightCheckbox的状态发生更改时运行选择更新代码:

class RightCheckbox(IRightBodyTouch, MDCheckbox):
    def on_state(self, instance, new_state):
        super(RightCheckbox, self).on_state(instance, new_state)
        MDApp.get_running_app().update_selections()

然后将update_selections()方法添加到您的应用:

class MainApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.selections = []  # this will hold the items selected
        self.view = View()

    def update_selections(self):
        # some checkbox has changed, so update the selections
        self.selections = []
        for w in self.root.ids.scroll.children:
            if w.ids.check.state == 'down':
                self.selections.append(w.text)
        print('selected items:', self.selections)

相关问题