Kivy中ScrollView添加Widget无显示问题求助
解决Kivy MDScrollView中动态生成列表项不显示的问题
问题核心
动态生成的OneLineListItem无法显示,根源在于列表容器的布局参数配置错误,导致MDScrollView无法识别超出容器的内容;同时触发生成条目的按钮未绑定对应方法,无法触发列表生成逻辑。
修复方案
调整kv文件中「Item List」区域的布局参数,并给Add按钮添加触发事件:
- 给
MDScrollView设置size_hint_y: 1,确保它占满父容器MDBoxLayout的垂直空间 - 给
MDList设置size_hint_y: None和height: self.minimum_height,让列表高度根据内容自动计算,超出MDScrollView的部分会触发滚动 - 给Add按钮绑定
on_press: app.test(),点击时调用生成条目的方法
修改后的完整代码
Python文件(无需调整)
from kivymd.app import MDApp from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout from kivy.core.window import Window from kivy.config import Config from kivymd.uix.list import OneLineListItem # 设置窗口尺寸 Config.set('graphics', 'width', '1000') Config.set('graphics', 'height', '600') Config.set('graphics', 'resizable', False) Window.size = (1000, 600) class MainApp(MDApp): def build(self): return Builder.load_file("interface.kv") def test(self): for i in range(20): item = OneLineListItem( text=f'Items number {i}' ) self.root.ids.items.add_widget(item) MainApp().run()
Kivy文件(修改关键部分)
#:kivy 2.3.0 FloatLayout: #--------------------Header------------------- Image: source: 'ex.png' size_hint: (0.3,0.3) pos_hint: {'x':-.05,'y': .75} MDLabel: text: "Invoice System" font_size: '50sp' halign: 'center' pos_hint: {'y': .4} #---------------Item---------------- MDTextField: mode: 'fill' hint_text: "???" size_hint: (.4, .1) pos_hint: {'x': .05, 'y': .65} MDTextField: mode: 'fill' hint_text: "???" size_hint: (.14, .1) pos_hint: {'x': .46, 'y': .65} MDTextField: mode: 'fill' hint_text: "???" size_hint: (.14, .1) pos_hint: {'x': .61, 'y': .65} MDFillRoundFlatIconButton: style: 'filled' text: "Add" size_hint: (.1, .1) pos_hint: {'x': .79, 'y': .65} on_press: app.test() # 添加触发事件 #------------ Item List -------------------- MDBoxLayout: md_bg_color: '#B5C0D0' size_hint: (.846, .37) pos_hint: {'x':.05, 'y': .25} padding: 10 orientation: 'vertical' MDScrollView: size_hint_y: 1 # 占满父容器垂直空间 MDList: id: items size_hint_y: None height: self.minimum_height # 高度随内容自动调整 #------------ Last button -------------------- MDFillRoundFlatIconButton: style: 'filled' text: "Make Invoice" size_hint: (.21, .15) pos_hint: {'x': .35, 'y': .08}
效果验证
点击Add按钮后,20条OneLineListItem会被添加到列表中,超出MDScrollView高度的内容可通过滚动查看。
内容的提问来源于stack exchange,提问作者Svin
相关产品推荐
相关产品推荐

