[英]custom widget triggers another custom widget's on_touch_down event
[英]want to access the widget's (here OneLineListItem) text and id when it is clicked using on_touch_down method
目標:
- 僅在按下OneLineListItem
小部件時調用my_callback()
function,否則什么也不做。
解釋這些事情:
- 請解釋我如何在按下 OneLineListItem 中的任何一個時調用OneLineListItem
my_callback()
,使用 on_touch_down() function
- 還解釋為什么我們在else
塊中添加super(Touch, self).on_touch_down(touch)
當前代碼的問題:
- 不要給出任何錯誤,但代碼不能按我的意願工作。
on_touch_down()
方法不起作用(想了解它是如何工作的,我剛剛從 kivy 的文檔中復制了它)。
from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.list import OneLineListItem
from kivy.uix.widget import Widget
helper_string = """
Screen:
Touch:
ScrollView:
MDList:
id: containers
"""
class MyApp(MDApp):
def build(self):
screen = Builder.load_string(helper_string)
return screen
def on_start(self):
# createing the OneLineListItem
item_1 = OneLineListItem(text='subject_1', id='item1')
item_2 = OneLineListItem(text='subject_2', id='item2')
item_3 = OneLineListItem(text='subject_3', id='item3')
# adding the above OneLineListItem into MDList
self.root.ids.containers.add_widget(item_1)
self.root.ids.containers.add_widget(item_2)
self.root.ids.containers.add_widget(item_3)
class Touch(Widget):
def on_touch_down(self, touch):
app = MDApp.get_running_app()
# gets all the OneLineListItem in subject_wid_list
subject_wid_list = app.root.ids.containers.children
# plz explain this part briefly. have lots of confusion about .collide_point()
# also explain why we are adding super(...).on_touch_down()
# iterating in the list and checking for collision of widget with touched coordinates.
for child in subject_wid_list:
if child.collide_point(*touch.pos):
print('touched one of the OneLineListItem widget')
self.my_callback()
else:
print('touched something else other than OneLineListItem widget')
return super(Touch, self).on_touch_down(touch)
def my_callback(self):
pass
MyApp().run()
您可以通過實例訪問小部件文本和 ID:
def mycallback(self,instance):
m=instance.id
x=instnace.text
它決定了行,你可以處理它。 添加時必須將 id 添加到小部件。 我沒有用 on_touch_down 嘗試過,但我用 on_press 試過了,它有效。
您可以在 add_widget 時調用 my_callback function,如下所示:
self.ids.scroll.add_widget(OneLineListItem(text='as you want' ,id=str(i),halign="right",on_press=self.mycallback))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.