如何自动设置MDCard高度使其适配内部MDLabel无需手动指定尺寸
实现方案
你只需要修改KV代码中MDCard和内部MDLabel的尺寸配置即可,无需额外写逻辑代码,修改点如下:
- MDLabel配置
新增两个属性让标签高度自动适配文本内容:size_hint_y: None取消垂直方向的尺寸继承height: self.texture_size[1] + self.padding[1] * 2高度等于文本渲染后的实际高度加上上下内边距
- MDCard配置
取消固定高度设置,改为自适应子控件总高度:- 把原来的
size: 280, 200替换为width: 280dp+height: self.minimum_height - 保留
size_hint: None, None配置即可
- 把原来的
修改后完整可运行代码
from kivy.lang import Builder from kivymd.app import MDApp from kivy.core.window import Window Window.size = (300, 530) KV = """ MDBoxLayout: orientation: 'vertical' ScrollView: MDGridLayout: cols: 1 adaptive_height: True padding: '10dp', '15dp' spacing: '15dp' MDCard: orientation: 'vertical' size_hint: None, None width: 280dp height: self.minimum_height MDLabel: markup: True padding: [15, 15] size_hint_y: None height: self.texture_size[1] + self.padding[1] * 2 text: ''' [size=25][b]Ford[/b][/size] If mdlabel text becomes too many to fit into the specified mdcard size,\n the text overslaps other things closeby..\n So my question: How do I set MDCard height to automatically\n adjusts accordingly to the height/size of widgets inside of it.\n Thanks in Advance!! ''' MDCard: orientation: 'vertical' size_hint: None, None width: 280dp height: self.minimum_height MDLabel: markup: True padding: [15, 15] size_hint_y: None height: self.texture_size[1] + self.padding[1] * 2 text: ''' [size=25][b]Ford[/b][/size] If mdlabel text becomes too many to fit into the specified mdcard size,\n the text overslaps other things closeby..\n So my question: How do I set MDCard height to automatically\n adjusts accordingly to the height/size of widgets inside of it.\n Thanks in Advance!!\n 额外追加文本测试自适应效果\n 额外追加文本测试自适应效果\n 额外追加文本测试自适应效果 ''' """ class Example(MDApp): def build(self): return Builder.load_string(KV) Example().run()
运行后可以看到第二个卡片因为文本更多,高度会自动拉长,不会出现内容溢出遮挡的问题。
内容的提问来源于stack exchange,提问作者Edwin
相关产品推荐
相关产品推荐

