我正在运行 Lazarus v0.9.30(32 位编译器)。
我有一个带有标准 TStringGrid 的 TForm。网格具有以下属性集。RowCount = 5,ColumnCount = 5,FixedCols = 0,FixedRows = 0。
我在 Google 上搜索了一些代码,这些代码向我展示了如何在用户单击 TStringGrid 单元格时更改单元格颜色并向单元格添加一些文本。一切正常,我稍微扩展了它以在 GridClick 事件上打开和关闭颜色/文本。
我的问题更多是为了更好地理解代码中某些元素背后的目的。
有一组 Foregroud (FG) 和 Background (BG) TColor 对象。它们是否用于存储在 GridClick 事件上设置的单元格颜色属性,因此如果 DrawCell 事件因任何原因需要再次触发,则单元格可以重绘自身?您可以避免使用 TColors 数组并根据需要在 DrawCell 事件中设置颜色/文本吗?
如果您需要使用数组,我会假设维度必须与 Grid.ColCount 和 Grid.RowCount 匹配(即通过 Form.Create 中的 SetLength 调用设置)
有没有办法检测到您正在单击字符串网格的 5 x 5 单元格之外(即在空白处),从而防止 GridClick 调用 DrawCell 事件。无论您在哪里单击,您始终会获得 Row 和 Col 的有效值。
unit testunit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
ExtCtrls, Menus, ComCtrls, Buttons, Grids, StdCtrls, Windows, Variants,
LCLType;
type
{ TForm1 }
TForm1 = class(TForm)
Grid: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure GridClick(Sender: TObject);
procedure GridDrawCell(Sender: TObject; aCol, aRow: Integer;
aRect: TRect; aState: TGridDrawState);
end;
var
Form1: TForm1;
implementation
var
FG: array of array of TColor;
BG: array of array of TColor;
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
var
Col, Row: integer;
begin
// Set the sizes of the arrays
SetLength(FG, 5, 5);
SetLength(BG, 5, 5);
// Initialize with default colors
for Col := 0 to Grid.ColCount - 1 do begin
for Row := 0 to Grid.RowCount - 1 do begin
FG[Col, Row] := clBlack;
BG[Col, Row] := clWhite;
end;
end;
end;
procedure TForm1.GridDrawCell(Sender: TObject; aCol, aRow: Integer;
aRect: TRect; aState: TGridDrawState);
var
S: string;
begin
S := Grid.Cells[ACol, ARow];
// Fill rectangle with colour
Grid.Canvas.Brush.Color := BG[ACol, ARow];
Grid.Canvas.FillRect(aRect);
// Next, draw the text in the rectangle
Grid.Canvas.Font.Color := FG[ACol, ARow];
Grid.Canvas.TextOut(aRect.Left + 22, aRect.Top + 2, S);
end;
procedure TForm1.GridClick(Sender: TObject);
var
Col, Row: integer;
begin
Col := Grid.Col;
Row := Grid.Row;
// Set the cell color and text to be displayed
if (Grid.Cells[Col,Row] <> 'Yes') then
begin
BG[Col, Row] := rgb(131, 245, 44);
FG[Col, Row] := RGB(0, 0, 0);
Grid.Cells[Col, Row] := 'Yes'
end {if}
else
begin
BG[Col, Row] := rgb(255, 255, 255);
FG[Col, Row] := RGB(255, 255, 255);
Grid.Cells[Col, Row] := '';
end; {else}
end;
end.