2015-06-03 71 views
3

我試圖用Kivy創建一個視圖,該視圖具有默認選擇的所有選項列表,用戶可以選擇取消選擇一些條目(通過單擊複選框或任何位於行)。Kivy多選複選框

單擊行項目的標籤部分工作,但我注意到點擊複選框不會改變選擇,我不能解決如何解決(我嘗試了幾種不同的狀態綁定,我離開了他們在示例代碼中註釋掉了)

下面是一個快速示例,顯示了我嘗試過的內容。

from kivy.app import App 
from kivy.properties import StringProperty, ListProperty 
from kivy.uix.boxlayout import BoxLayout 
from kivy.uix.selectableview import SelectableView 
from kivy.uix.togglebutton import ToggleButtonBehavior 
from kivy.adapters.models import SelectableDataItem 
from kivy.lang import Builder 

Builder.load_string(""" 
#: import ListAdapter kivy.adapters.listadapter.ListAdapter 
#: import Factory kivy.factory.Factory 

<MyListItem>: 
    height: 50 

    on_state: root.is_selected = args[1] == "down" 
    state: "down" if root.is_selected else "normal" 

    BoxLayout: 
     spacing: 10 

     CheckBox: 
      on_state: root.is_selected = args[1] == "down" 
      state: "down" if root.is_selected else "normal" 
      # on_state: root.state = args[1] 
      # state: root.state 

     Label: 
      text: root.name 

<Page>: 
    orientation: "vertical" 

    ListView: 
     id: LV 
     adapter: ListAdapter(data=root.data, cls=Factory.MyListItem, args_converter=root.args_converter, selection_mode="multiple", propagate_selection_to_data=True) 

    Button: 
     size_hint_y: None 
     text: "print selection" 
     on_press: print(LV.adapter.selection) 
""") 

class MyListItem(ToggleButtonBehavior, SelectableView, BoxLayout): 
    name = StringProperty() 

    def __repr__(self): 
     return "%s(name=%r)" % (type(self).__name__, self.name) 

    def on_state(self, me, state): 
     print me, state 
     if state == "down": 
      self.select() 
     else: 
      self.deselect() 
     # self.is_selected = state == "down" 

class DataItem(SelectableDataItem): 
    def __init__(self, name, **kwargs): 
     super(DataItem, self).__init__(**kwargs) 
     self.name = name 

    def __repr__(self): 
     return "%s(name=%r, is_selected=%r)" % (type(self).__name__, self.name, self.is_selected) 


class Page(BoxLayout): 
    data = ListProperty() 

    def __init__(self, **kwargs): 
     super(Page, self).__init__(**kwargs) 
     self.data = [DataItem("Item {}".format(i), is_selected=True) for i in range(10)] 

    def args_converter(self, index, data_item): 
     return { 
      "index": index, 
      "name": data_item.name, 
     } 


class ExampleApp(App): 
    def build(self): 
     return Page() 


if __name__ == "__main__": 
    ExampleApp().run() 

我使用Kivy v1.9.1-dev


編輯:我計算出如何讓所有的條目預先選擇,我已經更新了代碼,把問題的一部分出。

回答