Home > front end >  How Can I Paint All The Column Title Cells Of A TStringGrid Different Colours?
How Can I Paint All The Column Title Cells Of A TStringGrid Different Colours?

Time:01-06

I am running Lazarus 0.9.30.2.

I have a TForm on which there is a TStringGrid. Each column title is a TGridColumns object that I added dynamically to the grid at run time. Each column title has an object associated with it (that I created and have stored in a TList). I want to paint the background of the column title cells of the string grid, but I don't want all of the cells to be the same colour. Depending on the value of one of the properties in the object associated with the column title, the colour will vary.

I know that there are answers regarding how to paint TStringGrid cells in Stackoverflow (example), that talk about using the string grids DrawCell event to paint the cells, but I'm not sure how to invoke this procedure.

Is the correct approach to have another procedure that identifies the cell of interest (ie identifies the cells 'Rect' property), sets the colour that I want, that then invokes a common DrawCell procedure of the grid to do the actual colouring?

CodePudding user response:

There's a better event for this purpose, the OnPrepareCanvas. This event is being fired whenever the cell is preparing to draw itself and in that stage you can modify some of the canvas attributes, like brush color for painting the background. So what you need is to store the color somewhere:

type
  TTmColumnTitle = class(TTmObject)
  private
    FCellColor: TColor;
  public
    property CellColor: TColor read FCellColor write FCellColor;
  end;

And write the handler for the OnPrepareCanvas event:

procedure TForm1.StringGrid1PrepareCanvas(sender: TObject; aCol, aRow: Integer;
  aState: TGridDrawState);
var
  ColumnTitle: TTmColumnTitle;
begin
  if ARow = 0 then
  begin
    ColumnTitle := TTmColumnTitle(StringGrid1.Objects[ACol, ARow]);
    if Assigned(ColumnTitle) then
      StringGrid1.Canvas.Brush.Color := ColumnTitle.CellColor;
  end;
end;  

Object Inspector with OnPrepareCanvas event shown:

  • Related