1
votes

In firemonkey (RAD Studio 10.3), I am working with a TStringGrid connected to a database and I want to change the text alignment of a specific column. How can I do that? Changing HorzAlign in TextSettings property, changes the alignment of all columns.

I tried the suggested solution in this page and did not work! In newer versions of Firemonkey the below solution code results in an error.

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

There is no CreateCellControl function in TColumn Class anymore to be Overrided! This is the error I got:

Method CreateCellControl not found in base class.

2

2 Answers

3
votes

In the OnDrawColumnCell and/or OnDrawColumnHeader events you can use a TTextLayout for the purpose. As in the following example showing drawing the cells with three different alignments. The same can be applied when drawing the headers:

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 has many other useful options and properties, so I recommend to take a look at the documentation.

0
votes

Apart from the change already identified InflateRect(rf, 0, 0), to allow for existing data to be displayed correctly:

Change

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

to

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

This worked for me.