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

Builder字符串中无法调用ScrollView的self.minimum_height,如何设置高度?

解决Builder字符串中ScrollView高度设置问题

在使用Builder.load_string编写KV字符串时,无法直接调用ScrollView的self.minimum_height属性,需要通过配置内部布局和ScrollView自身的尺寸属性来实现高度控制。

原代码问题分析

你的原代码中,GridLayout未设置size_hint_y: None和height: self.minimum_height,导致ScrollView无法识别内容高度,同时ScrollView自身也没有明确的尺寸约束。

修改后的代码示例

Builder.load_string("""
<MenuScreen>:
    name: 'menu'
    layoutContent: layoutContent
    FloatLayout:
        ScrollView:
            # 方式1:用相对比例设置高度,占父容器80%垂直空间
            size_hint_y: 0.8
            pos_hint: {'center_y': 0.5, 'x': 0}
            # 方式2:固定高度,比如设置为400像素
            # height: 400
            GridLayout:
                id: layoutContent
                cols: 2
                rows: 10
                size_hint_y: None  # 必须关闭垂直方向自动缩放
                height: self.minimum_height  # 让布局高度适配所有子控件总高度
                MDRectangleFlatButton:
                    text: 'Goto settings'
                    on_press: root.manager.current = 'settings'
""")

关键配置说明

  • 内部布局(GridLayout):必须设置size_hint_y: None,否则height属性会被自动缩放覆盖;再通过height: self.minimum_height让布局高度根据子控件总高度自动调整,这是ScrollView能正常滚动的前提。
  • ScrollView自身高度:有两种设置方式:
    1. 使用size_hint_y设置相对父容器的高度比例(比如0.8表示占父容器80%垂直空间),配合pos_hint调整位置;
    2. 直接设置height为固定像素值(比如400),适合需要固定高度的场景。

如果需要ScrollView填充整个父容器,直接设置size_hint: 1, 1即可,它会自动占满FloatLayout的全部空间。

内容的提问来源于stack exchange,提问作者Pol Arbiol i Rakuljic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:18:38