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

如何调整Kivymd中MDSegmentedControl的整体宽度,避免超出屏幕?

解决Kivymd MDSegmentedControl宽度溢出问题

你的代码核心问题是MDCard未设置布局管理器,导致子组件布局混乱,加上adaptive_width=True让MDSegmentedControl根据内容自动扩展,容易超出屏幕范围。以下是修复后的代码:

from kivy.lang import Builder
from kivymd.app import MDApp

KV = '''
MDScreen:
    MDCard:
        # 添加BoxLayout作为布局管理器,规范子组件排列逻辑
        BoxLayout:
            orientation: "horizontal"
            padding: "20dp"
            spacing: "20dp"
            size_hint: 1, None
            height: "60dp"
            pos_hint: {"center_y": .5}

            MDLabel:
                size_hint: None, 1
                width: 200
                text: 'Gender'
                halign: "left"
                valign: "center"
                text_size: self.size

            MDSegmentedControl:
                # 用size_hint限制宽度占比,替代自适应宽度避免溢出
                size_hint_x: 0.6
                adaptive_height: True

                MDSegmentedControlItem:
                    text: "Male"

                MDSegmentedControlItem:
                    text: "Female"
'''


class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"
        return Builder.load_string(KV)


Example().run()

关键修改说明:

  • 给MDCard内部添加BoxLayout,通过orientation设置横向排列,搭配padding和spacing控制组件间距,解决布局拥挤问题
  • 调整MDSegmentedControl宽度逻辑:移除adaptive_width=True,改用size_hint_x: 0.6让它占父容器60%宽度;也可以设置size_hint_x: None+width: 300来固定宽度
  • 给MDLabel补充halign、valign和text_size属性,保证文本居中显示,避免排版错乱
  • 给BoxLayout设置固定height和size_hint:1, None,确保卡片高度合适,不会无限制拉伸

内容的提问来源于stack exchange,提问作者cryptotheo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:05:59