delphi中,当StringGrid中的值变化时,字体颜色跟着改变或者背景颜色改变,要怎么实现

2025-02-24 07:25:11
推荐回答(2个)
回答1:

用stringgrid的DrawCell控制背景色

-------------------------

见下面的demo,界面上放button==>用于填充数据(btn1),放stringgrid==>用于显示数据(strngrd1)
--------------------------

procedure TForm1.btn1Click(Sender: TObject);
const
Cn_Row_Cnt = 3;
Cn_Col_Cnt = 3;
var
iRowNo,iColNo:Integer;
i:Integer;
begin
for i := 0 to Grd1.RowCount -1 do
Grd1.Rows[i].Clear;

Grd1.RowCount := Cn_Row_Cnt;
Grd1.ColCount := Cn_Col_Cnt;
Grd1.FixedCols:=0;
Grd1.FixedRows:=0;

for iRowNo := 0 to Cn_Row_Cnt do
for iColNo := 0 to Cn_Col_Cnt do
Grd1.Cells[iColNo,iRowNo] := Format('第%d行第%d列',[iRowNo,iColNo]);
end;

procedure TForm1.Grd1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
iBackColor,iFrontColor:Integer;
begin
//这里根据你的需要得到各种颜色什么的
case (ARow mod 2) of
0:
begin
iBackColor := clYellow; //背景黄色
iFrontColor := clRed; //字体红色
end;
1:
begin
iBackColor := clSkyBlue;//背景天蓝
iFrontColor := clBlack; //字体黑色
end;
end;

with TStringGrid(Sender) do
begin
Canvas.Brush.Color := iBackColor;
Canvas.Font.Color := iFrontColor;
Canvas.FillRect(Rect);
Canvas.TextRect(Rect,Rect.Left+2,Rect.Top+2,Cells[ACol,ARow]);//没这句话,会没有字的
end;
end;

回答2:

很简单,在OnDrawCell事件中填写(当内容为"123"时会变色):
var
KeyWord: string = '123';

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
if StringGrid1.Cells[ACol, ARow] = KeyWord then
begin
StringGrid1.Canvas.Brush.Color := clYellow;
StringGrid1.Canvas.FillRect(Rect);
StringGrid1.Canvas.Font.Color := clRed;
StringGrid1.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, KeyWord);
end;
end;