In Delphi, how can I create a class derived from the TStringGrid class such that the TObject array associated with the grids cells is of a more specific type for example TColor which would be used to specify the colour of the cell?
1
votes
2 Answers
6
votes
type
TStringColorGrid = class(TStringGrid)
private
function GetColor(ACol, ARow: Integer): TColor;
procedure SetColor(ACol, ARow: Integer; AValue: TColor);
public
property Colors[ACol, ARow: Integer]: TColor read GetColor write SetColor;
end;
function TStringColorGrid.GetColor(ACol, ARow: Integer): TColor;
begin
Result := TColor(inherited Objects[ACol, ARow]);
end;
procedure TStringColorGrid.SetColor(ACol, ARow: Integer; AValue: TColor);
begin
inherited Objects[ACol, ARow] := TObject(AValue);
end;
2
votes
TStringGrid can hold a TObject for each cell. TColor doesn't inherit from TObject so it doesn't work.
You could cast a TColor to a TObject but this would be a bad solution prone to future issues. And this would not work for any type (Only those having at most the size of a pointer).
The best solution is to "box" your data into a TObject and save the instance of such an object into the StringGrid.
TMyBoxingColorObject = class
Data : TColor; // Or any other datatype
end;
Don't forget to create and free the object as needed!
You can also use generics if you have a lot of different types to box.
TColor
type isn't a class and so doesn't belong to any class hierarchy. ATColor
isn't aTObject
. It so happens, however, that aTColor
is a 32-bit integer and therefore fits into aTObject
(=pointer) variable on all platforms used today (32 bit and 64 bit).TButton
,TBitmap
, andTStringList
are classes, however, so aTStringList
instance is aTObject
. – Andreas Rejbrand