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

如何修改RAD Studio 11中TListBox所有项的字体?

解决RAD Studio 11中TListBox所有项统一设置字体的问题

关键错误分析

你代码中的核心问题有两个:

  1. 调用ingredientsDataBase->Items->Add("newIngredient")后,额外创建并销毁TListBoxItem属于冗余操作,且会导致设置无效。
  2. 修改StyledSettings时误用了<<操作符(该操作符是添加集合元素),但实际需要移除Family和Size,让自定义字体设置生效——默认情况下StyledSettings包含这两项,会强制ListBoxItem继承父控件的字体样式。

正确实现方式

方法1:动态添加Item时直接配置字体(推荐)

直接创建TListBoxItem实例,完成样式和字体配置后添加到ListBox,无需通过Items->Add:

__fastcall TIngredientCreator::addButtonClick(TObject *Sender)
{
    // 创建新的ListBoxItem,以ListBox为所有者
    TListBoxItem *lbItem = new TListBoxItem(ingredientsDataBase);
    try
    {
        lbItem->Parent = ingredientsDataBase;
        // 从StyledSettings中移除Family和Size,解除父控件字体继承
        lbItem->StyledSettings = lbItem->StyledSettings >> TStyledSetting::Family >> TStyledSetting::Size;
        // 设置自定义字体属性
        lbItem->TextSettings->Font->Family = "Algerian";
        lbItem->TextSettings->Font->Size = 18;
        lbItem->Text = "newIngredient";
    }
    catch(...)
    {
        delete lbItem;
        throw;
    }
}

方法2:批量修改已有ListBoxItem的字体

如果需要对所有已存在的Item统一设置字体,可以遍历ListBox的Items集合:

void __fastcall TIngredientCreator::SetAllListBoxItemsFont()
{
    for (int i = 0; i < ingredientsDataBase->Items->Count; ++i)
    {
        TListBoxItem *lbItem = ingredientsDataBase->ItemByIndex(i);
        if (lbItem)
        {
            lbItem->StyledSettings = lbItem->StyledSettings >> TStyledSetting::Family >> TStyledSetting::Size;
            lbItem->TextSettings->Font->Family = "Algerian";
            lbItem->TextSettings->Font->Size = 18;
        }
    }
}

补充说明

  • TStyledSettings是样式集合,默认包含Family、Size等属性,这些属性会让ListBoxItem强制继承父控件的样式,只有移除这些设置后,自定义的TextSettings.Font才会生效。
  • 你手动在Object Inspector中修改ListBoxItem字体生效,是因为IDE自动帮你移除了对应的StyledSettings项。

内容的提问来源于stack exchange,提问作者Loststar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:55:32