KivyMD中MDLabel的pos_hint仅X轴生效,Y轴无法移动求助
问题原因及解决办法
你的MDLabel无法通过pos_hint的y属性调整垂直位置,核心原因是它被放在了垂直方向的MDBoxLayout里。
垂直MDBoxLayout的布局逻辑是强制子元素沿垂直方向(从上到下)排列,它会自动接管所有子元素的垂直位置分配,你设置的y方向pos_hint会被布局规则覆盖,所以只有x方向的设置能生效。
解决办法
方法1:将MDLabel移出BoxLayout,直接作为页面子控件
如果需要完全自由的定位,把MDLabel从外层的垂直MDBoxLayout中拿出来,直接作为HomePage的子元素(前提是HomePage继承自支持自由定位的布局,比如FloatLayout或Screen,后者默认是RelativeLayout,也支持pos_hint):
<HomePage>: md_bg_color: [34/255, 0/255, 64/255, 1] background_normal: '' # 直接将MDLabel作为页面子控件,可自由定位 MDLabel: text: 'Shop' bold: True font_size: 50 theme_text_color: 'Custom' color: [0/255, 186/255, 198/255, 1] pos_hint: {'x':.13, 'y':.18} MDBoxLayout: orientation: 'vertical' padding: '5dp' adaptive_height: True MDTextField: mode: 'round' text: 'username'
方法2:在BoxLayout中嵌套FloatLayout实现自由定位
如果必须把MDLabel留在BoxLayout里,可以在BoxLayout中添加一个FloatLayout作为容器,把MDLabel放在这个容器里,这样就能在容器内自由调整位置:
<HomePage>: md_bg_color: [34/255, 0/255, 64/255, 1] background_normal: '' MDBoxLayout: orientation: 'vertical' MDBoxLayout: padding: '5dp' adaptive_height: True # 添加FloatLayout作为容器 FloatLayout: adaptive_height: True # 或设置固定height MDLabel: text: 'Shop' bold: True font_size: 50 theme_text_color: 'Custom' color: [0/255, 186/255, 198/255, 1] pos_hint: {'x':.13, 'y':.18} MDTextField: mode: 'round' text: 'username'
内容的提问来源于stack exchange,提问作者Signore
相关产品推荐
相关产品推荐

