如何在ScrollView
或ListView
中添加我的小部件以滚动它?
我已经编写了一段代码,但它没有成功,这是我的 main.py :
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from random import random
class chat_history(BoxLayout):
def profile(self):
return random(),random(),random()
Builder.load_file('widg.kv')
class myApp(App ):
def build(self):
x=BoxLayout(orientation='vertical')
s=ScrollView()
for i in range(1,21):
x.add_widget(chat_history(height=50))
s.add_widget(x)
return s
myApp().run()
这是我的 kv文件:
<chat_history>:
height:100
BoxLayout:
height:50
name:'haha very funny '
size_hint_y:None
id:cv
orientation:'horizontal'
canvas:
Color:
rgb:root.profile()
Ellipse:
pos:root.pos
Label:
text_hint:{'x':0,'y':0.1}
pos:root.pos
size_hint_x:0.7
height:cv.height
text:cv.name
id:lbl
答案 0 :(得分:0)
首先,您应该阻止布局自动调整其高度到其父窗口小部件(size_hint_y = None
)的高度。
另一方面,确保高度可以滚动。您必须明确指定布局高度。
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from random import random
kv_text = '''
<chat_history>:
size_hint_y: None
height:100
BoxLayout:
height:50
name:'haha very funny '
size_hint_y:None
id:cv
orientation:'horizontal'
canvas:
Color:
rgb:root.profile()
Ellipse:
pos:root.pos
Label:
text_hint:{'x':0,'y':0.1}
pos:root.pos
size_hint_x:0.7
height:cv.height
text:cv.name
id:lbl
'''
class chat_history(BoxLayout):
def profile(self):
return random(),random(),random()
class myApp(App ):
def build(self):
Builder.load_string(kv_text)
x=BoxLayout(orientation='vertical', size_hint_y=None) #<<<<<<<<<<<
x.bind(minimum_height=x.setter('height')) #<<<<<<<<<<<
s=ScrollView()
for i in range(1,21):
x.add_widget(chat_history(height=50))
s.add_widget(x)
return s
myApp().run()