如何在firemonkey TGrid / TStringGrid中为特定列设置文本对齐方式?

时间:2019-07-20 10:05:39

标签: delphi firemonkey tstringgrid rad-studio tgrid

在firemonkey(RAD Studio 10.3)中,我正在使用连接到数据库的TStringGrid,并且我想更改特定列的文本对齐方式。我怎样才能做到这一点?更改TextSettings属性中的HorzAlign,更改所有列的对齐方式。

我在this page中尝试了建议的解决方案,但没有成功!在更新版本的Firemonkey中,以下解决方案代码导致错误。

type TSpecificColumn = class(TColumn)
protected
  function CreateCellControl: TStyledControl;override;
end;

TColumn类中不再有CreateCellControl函数要被覆盖!这是我得到的错误:

在基类中找不到方法CreateCellControl。

2 个答案:

答案 0 :(得分:2)

OnDrawColumnCell和/或OnDrawColumnHeader事件中,您可以使用TTextLayout来达到目的。如以下示例所示,绘制具有三个不同路线的单元格。绘制标题时可以应用相同的方法:

uses
  ...
  fmx.textlayout;


procedure TForm11.Grid1DrawColumnCell(Sender: TObject; const Canvas: TCanvas;
  const Column: TColumn; const Bounds: TRectF; const Row: Integer;
  const Value: TValue; const State: TGridDrawStates);
var
  tl: TTextLayout;
  rf: TRectF;    // added
begin
  tl := TTextLayoutManager.DefaultTextLayout.Create;
  try
    tl.BeginUpdate;
    try
      // added from here
      rf := Bounds;
      InflateRect(rf, -2, -2);
      if (TGridDrawState.Selected in State) or
         (TGridDrawState.Focused in State) or
         (TGridDrawState.RowSelected in State)
      then
        Canvas.Fill.Color := TAlphaColors.LightBlue
      else
        Canvas.Fill.Color := TAlphaColors.White;

      Canvas.FillRect(rf, 0, 0, [], 1);
      // added until here

      tl.TopLeft := Bounds.TopLeft;
      tl.MaxSize := PointF(Column.Width, Column.Height);
      tl.Font.Size := 15;
      tl.Text := 'Some text'; // Value
      case Column.Index of
        0: tl.HorizontalAlign := TTextAlign.Leading;
        1: tl.HorizontalAlign := TTextAlign.Center;
        2: tl.HorizontalAlign := TTextAlign.Trailing;
      end;
    finally
      tl.EndUpdate;
    end;
    tl.RenderLayout(Canvas);
  finally
    tl.Free;
  end;
end;

enter image description here

TTextLayout还有许多其他有用的选项和属性,所以我建议看一下文档。

答案 1 :(得分:0)

除了已经确定的InflateRect(rf, 0, 0)更改之外,还可以正确显示现有数据:

更改

tl.Text := 'Some text'; // Value line 

tl.Text := [StringGrid name property].Cells[Column.Index,Row];

这对我有用。