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

MDTextField嵌套MDTextFieldHintText时font_size不生效的问题求助及解决方案

MDTextField嵌套MDTextFieldHintText时font_size不生效的问题求助及解决方案

最近在做KivyMD项目时碰到个棘手的小问题:我在MDTextField里面嵌套使用MDTextFieldHintText时,设置的font_size完全不生效;但如果单独用MDTextFieldHintText,调整font_size是正常的。

我之所以要固定用dp单位设置字体大小,是因为用户修改手机系统字体大小后,输入框里的提示文字会变形,甚至超出输入框的边界,体验很差。有没有朋友遇到过类似问题,或者有什么可行的解决思路?

我的环境是:Kivy==2.3.1,KivyMD用的是master分支的开发版本。

下面是能复现问题的代码:

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.textfield import MDTextField, MDTextFieldHintText
from kivy.metrics import dp

KV = """
MDScreen:
    md_bg_color: self.theme_cls.backgroundColor
    
    MDTextFieldHintText:
        text: "font_size works here..."
        theme_font_size: "Custom"
        font_size: "40dp"

    MDTextField:
        mode: "outlined"
        theme_font_size: "Custom"
        font_size: "50dp"
        
        MDTextFieldHintText:
            text: "...but font_size doesn't work here"
            theme_font_size: "Custom"
            font_size: "40dp"
"""

class MainApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Light"
        screen = Builder.load_string(KV)
        return screen

MainApp().run()

运行这段代码就能看到,单独的MDTextFieldHintText字体大小正常生效,但嵌套在输入框里的那个完全没变化。


我找到的解决方案

试了各种方法后,发现通过子类化MDTextField和MDTextFieldHintText,可以手动控制dp单位的字体大小,还能通过重写set_pos_hint_text方法调整提示文字的垂直位置,完美解决了问题。

解决后的代码如下:

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.textfield import MDTextField, MDTextFieldHintText
from kivy.metrics import dp

KV = """
MDScreen:
    md_bg_color: self.theme_cls.backgroundColor
    
    CustomMDTextField:
        mode: "outlined"
        theme_font_size: "Custom"
        font_size: "20dp"
        
        CustomMDTextFieldHintText:
            text: "Font size for HintText is 12dp"
"""

class CustomMDTextField(MDTextField):
    # 可选:调整提示文字的垂直位置
    def set_pos_hint_text(self, y, anim):
        super().set_pos_hint_text(y + dp(-5), anim)

class CustomMDTextFieldHintText(MDTextFieldHintText):
    # 手动设置dp单位的字体大小
    font_size = dp(12)

class MainApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Light"
        screen = Builder.load_string(KV)
        return screen

MainApp().run()

通过子类化这两个组件,我完全掌控了提示文字的字体大小,就算用户调整系统字体也不会影响到它,同时还能根据需要微调提示文字的位置,完美解决了之前的问题!


内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 07:28:02