Вы можете сделать это, используя событие OnDrawCell
(do неDefaultDraw
- False). Вот пример с регулярной TStringGrid
:
// Sample to populate the cells with the days of the week
procedure TForm1.FormShow(Sender: TObject);
var
r, c: Integer;
begin
StringGrid1.ColCount := 8; // Ignore fixed column and row for this example
StringGrid1.RowCount := 8;
for c := 1 to StringGrid1.ColCount - 1 do
for r := 1 to StringGrid1.RowCount - 1 do
StringGrid1.Cells[c, r] := FormatSettings.ShortDayNames[c];
end;
// Assign this to the StringGrid's OnDrawCell using the Object Inspector
// Events tab.
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
CellText: string;
begin
if (ARow > 0) and (ACol > 0) then
begin
CellText := StringGrid1.Cells[ACol, ARow];
if Pos('Sun', CellText) > 0 then
begin
StringGrid1.Canvas.Brush.Color := clRed;
StringGrid1.Canvas.FillRect(Rect);
end
else
StringGrid1.Canvas.Brush.Color := clWindow;
end;
// The '+ 4' is from the VCL; it's hard-coded when themes are enabled.
// You should probably check the grid's DrawingStyle to see if it's
// gdsThemed, and adjust as needed. I leave that as an exercise for you.
StringGrid1.Canvas.TextOut(Rect.Left + 4, Rect.Top + 4, CellText);
end;
Пример вывода точного кода выше:
Вот второй пример, который выводит только то, что вы хотите (за исключением я не конвертировать СОЛНЦЕ в колпачки):
procedure TForm1.FormShow(Sender: TObject);
var
r, c: Integer;
begin
StringGrid1.DefaultColWidth := 100;
StringGrid1.ColCount := 8;
StringGrid1.RowCount := 8;
for c := 1 to StringGrid1.ColCount - 1 do
for r := 1 to StringGrid1.RowCount - 1 do
StringGrid1.Cells[c, r] := FormatDateTime('mm/dd/yyyy ddd',
Date() + c + r - 1);
end;
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
CellText: string;
begin
if (ARow > 0) and (ACol > 0) then
begin
CellText := StringGrid1.Cells[ACol, ARow];
if Pos('Sun', CellText) > 0 then
StringGrid1.Canvas.Brush.Color := clRed
else
StringGrid1.Canvas.Brush.Color := clWindow;
StringGrid1.Canvas.FillRect(Rect);
end;
StringGrid1.Canvas.TextOut(Rect.Left + 4, Rect.Top + 4, CellText);
end;
Вот захват соответствует второму образцу:
В моем случае это не работает. У меня там тоже есть дата. Также это цвет только активных клеток. Я хотел бы покрасить весь столбец (включая фиксированную ячейку), если в имени столбца существует слово SUN. – user763539
Этот код также уничтожает содержимое моей ячейки, поэтому я не вижу ничего ... – user763539
Ум, нет, нет. :) Я добавлю захват экрана. Он также окрасит любую ячейку, содержащую текст 'Sun' (найденный с помощью' Pos' в коде выше), а не только активные ячейки. Вам нужно настроить код в соответствии с вашими конкретными потребностями; то, что я написал, было примером того, как это сделать, но это только отправная точка. :) –