You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在KivyMD的MDDialog中插入MDList并展示字典数据

问题原因与解决方法

首先明确:你不需要额外导入MDList相关配置,代码未达预期是两个逻辑错误导致的:

  • 第一个错误:DialogContent实例不匹配
    你在show_dialog方法中先创建了一个临时DialogContent实例调用check_conflicts添加列表项,但后续传入MDDialog的是全新的另一个DialogContent实例,这个新实例没有执行过添加列表项的逻辑,自然看不到内容。
  • 第二个错误:DialogContent尺寸设置无效
    KV代码中你给DialogContent设置了height: self.height、width: self.width,属于循环引用的无效配置,会导致内容区域尺寸异常,就算添加了控件也可能无法显示。
修正代码

首先修正show_dialog方法:

def show_dialog(self):
    if not self.dialog:
        # 先实例化唯一的content对象,执行列表添加逻辑
        content = DialogContent()
        content.check_conflicts(product_dict)
        self.dialog=MDDialog(
            title='Check products',
            type='custom',
            content_cls=content, # 直接传入已经加载好列表的content
            buttons=[
                MDFlatButton(
                    text='CANCEL',
                    theme_text_color="Custom",
                    text_color=self.theme_cls.primary_color,
                    on_release=self.close_dialog
                ),
                MDRaisedButton(
                    text='OK',
                    theme_text_color="Custom",
                    on_release=self.confirm_selection
                )
            ],
        )
    self.dialog.open()

然后修正KV中<DialogContent>的配置:

<DialogContent>
    confirm_check_in_list: confirm_check_in_list
    orientation: "vertical"
    spacing: dp(20)
    size_hint_y: None
    size_hint_x: None
    # 替换原来的无效尺寸设置,固定合适的宽高
    width: dp(400)
    height: dp(350)
    padding: dp(10)

    ScrollView:
        MDList:
            id: confirm_check_in_list

修改后运行代码,点击按钮弹出的对话框就能正常显示三条ThreeLineListItem内容。

内容的提问来源于stack exchange,提问作者Lucas Dueñas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:45:01