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

C++Builder 10.4中运行时数据绑定后FMX.TStringGrid列右对齐问题

C++Builder 10.4 FMX.TStringGrid 数据绑定列右对齐解决方法

核心问题分析

数据绑定的TStringGrid自定义列对齐时,直接依赖DefaultDrawCell会导致对齐设置失效,完全自定义绘制又容易丢失文本,本质是没有正确结合数据绑定的值获取与自定义文本绘制逻辑。

解决步骤与代码实现

  1. 设置目标列的DefaultDrawing为false
    无论是设计时还是运行时创建的列,都要将需要自定义对齐的列的DefaultDrawing属性设为false,确保触发OnDrawCell事件。

  2. 编写OnDrawCell事件处理函数
    在事件中区分目标列,自行获取绑定数据并绘制右对齐文本,其他列保留默认绘制:

    void __fastcall TForm1::StringGrid1DrawCell(TObject *Sender, const TRectF &Bounds, int Row, int Col, TGridDrawState State)
    {
        TStringGrid *Grid = static_cast<TStringGrid*>(Sender);
        // 替换为你的目标列索引(从0开始计数)
        const int TargetColIndex = 1;
    
        if (Col == TargetColIndex)
        {
            // 获取数据绑定的单元格值
            TValue CellValue = Grid->GetValue(Row, Col);
            String CellText = CellValue.ToString();
    
            // 绘制单元格背景,匹配默认样式
            if (State.Contains(TGridDrawState::Selected))
                Grid->Canvas->Fill->Color = Grid->SelectedColor;
            else
                Grid->Canvas->Fill->Color = (Row % 2 == 0) ? Grid->BackgroundColor : Grid->AlternatingRowColor;
            Grid->Canvas->FillRect(Bounds, 0, 0, AllCorners, 1);
    
            // 设置文本样式:右对齐+垂直居中
            Grid->Canvas->Font->Assign(Grid->Font);
            Grid->Canvas->TextAlign = TTextAlign::Trailing; // FMX中LTR语言下对应右对齐
            Grid->Canvas->TextVertAlign = TTextAlign::Center;
    
            // 内缩边界,避免文本贴边
            TRectF TextArea = Bounds;
            TextArea.Inflate(-2, -2);
            // 绘制文本
            Grid->Canvas->FillText(TextArea, CellText, false, 1, [], TTextAlign::Trailing, TTextAlign::Center);
        }
        else
        {
            // 非目标列使用默认绘制逻辑
            Grid->DefaultDrawCell(Grid->Canvas, Bounds, Row, Grid->GetValue(Row, Col), State);
        }
    }
    

关键注意事项

  • 不要调用Column->DefaultDrawCell:数据绑定场景下,该方法无法正确应用自定义对齐设置,需自行处理文本绘制。
  • 使用TTextAlign::Trailing实现右对齐:FMX中避免直接用Right,Trailing会自动适配文字方向,在中文、英文等LTR环境下就是右对齐。
  • 必须手动绘制单元格背景:否则单元格会显示透明,破坏原有视觉样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:20:44