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

KivyMD中MDFloatingActionButton未点击时无阴影问题求助

解决MDFloatingActionButton初始不显示阴影的问题

在KivyMD 1.2.0版本中,MDFloatingActionButton设置elevation属性后,默认不会在初始状态绘制阴影,只有点击交互后才会显示。可以通过以下两种方法解决:

方法一:通过KV语言绑定on_parent事件触发更新

修改你的KV代码,给按钮添加on_parent事件,手动调用阴影更新方法:

MDScreen:
    MDFloatingActionButton:
        icon: 'delete-outline'
        type: 'large'
        md_bg_color: 'green'
        icon_color: 'white'
        elevation: 5
        pos_hint: {'center_x': .5, 'center_y': .5}
        on_parent: self._update_elevation()

方法二:自定义按钮类初始化时触发更新

继承MDFloatingActionButton,在初始化方法中手动调用阴影更新逻辑:

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.button import MDFloatingActionButton

class CustomFAB(MDFloatingActionButton):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._update_elevation()

KV = '''
MDScreen:
    CustomFAB:
        icon: 'delete-outline'
        type: 'large'
        md_bg_color: 'green'
        icon_color: 'white'
        elevation: 5
        pos_hint: {'center_x': .5, 'center_y': .5}
'''

class Example(MDApp):
    def build(self):
        return Builder.load_string(KV)

Example().run()

原理:_update_elevation()是按钮内部负责计算并绘制阴影的方法,默认只有按钮状态变化(如按下、释放)时才会调用。手动触发这个方法,就能让按钮在初始状态就显示设置好的阴影。

内容的提问来源于stack exchange,提问作者大橋和季

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:42:10