首页 \ 问答 \ 从Kivy Recycleview获取选定节点(Get selected node from Kivy Recycleview)

从Kivy Recycleview获取选定节点(Get selected node from Kivy Recycleview)

我有一些使用ListViews在以前版本的Kivy中编写的程序。 使用ListViews,通过适配器获取所选节点非常容易。 但是,如何使用RecycleView进行此操作还不太清楚。 现在, rv.layout_manager.selected_nodes可用于获取所选值,但也有时候我对实际节点感兴趣。 此外,以下代码段可用于生成节点,但显然,它们不是RecycleView中的实际节点。

opts = rv.layout_manager.view_opts
for i in range(len(rv.data)):
    s = rv.view_adapter.get_view(i, rv.data[i], opts[i]['viewclass'])
    print s.text, s.selected

我有兴趣找到一种从RecycleView获取所选节点的方法。

完整代码:

import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
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

#Aside: the code in the string would need to be indented back one tab, but it's like this for SO formatting
Builder.load_string('''
<SelectableLabel>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
        rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
        Rectangle:
            pos: self.pos
            size: self.size
<RV>:
    viewclass: 'SelectableLabel'
    SelectableRecycleBoxLayout:
        key_selection: "True"
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: False
        touch_multiselect: True
        touch_deselect_last: True
''')


class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    ''' Adds selection and focus behaviour to the view. '''


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, index, 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, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected


class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': str(random.random())} for x in range(20)]


class TestApp(App):
    def build(self):
        self.rv = RV()
        self.rv.layout_manager.bind(selected_nodes=self.selectionChange)
        return self.rv

    def selectionChange(self, inst, val):
        print inst, val

if __name__ == '__main__':
    b = TestApp()
    b.run()

I've got some programs written in previous versions of Kivy that use ListViews. Using ListViews, it was quite easy to get the selected node via the adapter. However, it is much less clear how to do this with a RecycleView. Now, it is the case that rv.layout_manager.selected_nodes can be used to get the selected value, but there are also times where I'm interested in the actual node. Also, the following snippet can be used to generate the nodes, but apparently, they aren't the actual nodes in the RecycleView.

opts = rv.layout_manager.view_opts
for i in range(len(rv.data)):
    s = rv.view_adapter.get_view(i, rv.data[i], opts[i]['viewclass'])
    print s.text, s.selected

I'd be interested in finding a way of getting the selected node from the RecycleView.

Full code:

import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
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

#Aside: the code in the string would need to be indented back one tab, but it's like this for SO formatting
Builder.load_string('''
<SelectableLabel>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
        rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
        Rectangle:
            pos: self.pos
            size: self.size
<RV>:
    viewclass: 'SelectableLabel'
    SelectableRecycleBoxLayout:
        key_selection: "True"
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: False
        touch_multiselect: True
        touch_deselect_last: True
''')


class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    ''' Adds selection and focus behaviour to the view. '''


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, index, 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, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected


class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': str(random.random())} for x in range(20)]


class TestApp(App):
    def build(self):
        self.rv = RV()
        self.rv.layout_manager.bind(selected_nodes=self.selectionChange)
        return self.rv

    def selectionChange(self, inst, val):
        print inst, val

if __name__ == '__main__':
    b = TestApp()
    b.run()

原文:https://stackoverflow.com/questions/46739914
更新时间:2022-06-12 20:06

最满意答案

[有三个参数的bash手册页(注意我的重点):

以列出的顺序应用以下条件

  • 如果第二个参数是上面在CONDITIONAL EXPRESSIONS下列出的二进制条件运算符之一,则表达式的结果是使用第一个和第三个参数作为操作数的二进制测试的结果。 当有三个参数时, '-a''-o'运算符被认为是二元运算符。

  • 如果第一个参数是'!' ,该值是使用第二和第三个参数的双参数测试的否定。

  • 如果第一个参数完全是'(' ,第三个参数完全是')' ,那么结果就是第二个参数的单参数测试。

  • 否则,表达式是错误的。

换句话说, -a在这种情况下并不像你期望的那样发挥作用。 它实际上被视为逻辑和操作符,因为两者都是!bar被认为是真实的,他们的结果也是如此:

pax> if [ ! ] ; then echo yes ; fi
yes
pax> if [ bar ] ; then echo yes ; fi
yes

[各种各样的弱点,这就是为什么明智的bash编码器会使用[[相反:-)]


From the bash man page for [ with three arguments (note my emphasis):

The following conditions are applied in the order listed.

  • If the second argument is one of the binary conditional operators listed above under CONDITIONAL EXPRESSIONS, the result of the expression is the result of the binary test using the first and third arguments as operands. The '-a' and '-o' operators are considered binary operators when there are three arguments.

  • If the first argument is '!', the value is the negation of the two-argument test using the second and third arguments.

  • If the first argument is exactly '(' and the third argument is exactly ')', the result is the one-argument test of the second argument.

  • Otherwise, the expression is false.

In other words, -a is not acting as you expect it to in this case. It's actually being treated as the logical-and operator and, since both ! and bar are considered true, the result of anding them is also true:

pax> if [ ! ] ; then echo yes ; fi
yes
pax> if [ bar ] ; then echo yes ; fi
yes

The foibles of [ are many and varied, which is why sensible bash coders will use [[ instead :-)

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。