Delphi 12.1中TSpeedButton样式覆盖问题:找不到background资源及改色方法
问题描述
在Delphi 12.1中,将TSpeedButton的StyleLookup设置为segmentedbuttonmiddle后,尝试通过以下代码修改背景色,却无法找到名为background的样式资源:
SpeedButton1.StyleLookup := 'segmentedbuttonmiddle'; var Background: TRectangle; if SpeedButton1.FindStyleResource('background') <> nil then begin Background := SpeedButton1.FindStyleResource('background') as TRectangle; Background.Fill.Color := TAlphaColorRec.LightBlue; end;
原因分析
- 样式资源命名不匹配:
segmentedbuttonmiddle样式的TSpeedButton,其背景元素的资源名称并非background,而是fill(具体名称由Delphi 12.1的FMX默认样式定义决定)。不同内置样式会使用不同的资源命名规则,旧版本参考代码中的资源名称不适用于该样式。 - 样式未完成加载:设置
StyleLookup后,控件的样式资源可能尚未完成初始化,此时调用FindStyleResource会返回nil。
解决方法
1. 查找正确的样式资源名称并修改
针对segmentedbuttonmiddle样式,背景资源名称为fill,修改代码如下:
SpeedButton1.StyleLookup := 'segmentedbuttonmiddle'; // 确保控件样式已加载,可放在Form创建完成后执行 var FillRect: TRectangle; if SpeedButton1.FindStyleResource('fill') <> nil then begin FillRect := SpeedButton1.FindStyleResource('fill') as TRectangle; FillRect.Fill.Color := TAlphaColorRec.LightBlue; end;
2. 利用ApplyStyleLookup事件确保样式加载完成
控件的ApplyStyleLookup事件会在样式加载完成后触发,在此事件中查找资源更可靠:
procedure TForm1.SpeedButton1ApplyStyleLookup(Sender: TObject); var FillRect: TRectangle; begin inherited; if SpeedButton1.FindStyleResource('fill') <> nil then begin FillRect := SpeedButton1.FindStyleResource('fill') as TRectangle; FillRect.Fill.Color := TAlphaColorRec.LightBlue; end; end;
3. 自定义样式(静态修改)
如果动态修改仍有问题,可直接通过Style Designer修改segmentedbuttonmiddle样式的背景色:
- 打开Delphi的Style Designer,加载默认FMX样式文件。
- 定位到
segmentedbuttonmiddle样式节点,修改其背景元素的填充颜色。 - 将修改后的样式应用到
TSpeedButton上。
内容的提问来源于stack exchange,提问作者Peter Jones
相关产品推荐
相关产品推荐

