StringGrid Cells Delphi

时间:2013-03-21 18:27:09

标签: delphi colors click cells stringgrid

我根据数据列表编写了一些代码,用于在我的delphi应用程序中对我的stringgrid中的单个单元进行着色。

我现在需要在我的stringgrid上的OnDblClick事件中编写一些代码,该代码推断出一个单元格是否已着色,然后根据找到的结果继续进行。例如:

DOUBLE CLICK CELL  
IS CELL COLOURED  
  YES > PROCEED A  
  NO > PROCEED B

1 个答案:

答案 0 :(得分:1)

在将颜色绘制到预定义的TStringGrid.Objects属性中时存储颜色。当您需要检索它时,可以从ColumnRow坐标返回。这是一个简单的示例,根据单元格是否为奇数列,在clWhite中存储clBlackObjects,只需将存储的值显示为字符串时细胞被选中。它应该让你开始。

procedure TForm1.FormCreate(Sender: TObject);
var
  r, c: Integer;
const
  ColorSel: array[Boolean] of TColor = (clWhite, clBlack);
begin
  StringGrid1.RowCount := 10;
  StringGrid1.ColCount := 6;
  for c := 1 to StringGrid1.ColCount - 1 do
    for r := 1 to StringGrid1.RowCount - 1 do
    begin
      StringGrid1.Cells[c, r] := Format('C: %d R: %d', [c, r]);
      StringGrid1.Objects[c, r] := TObject(ColorSel[Odd(c)]);
    end;
end;

procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
  var CanSelect: Boolean);
begin
  ShowMessage(ColorToString(TColor(StringGrid1.Objects[ACol, ARow])));
end;

您可以轻松地在OnMouseUp事件中使用此功能来检测单元格中的颜色。删除StringGrid1SelectCell(使用Object Inspector,只删除事件的值)并将其添加为网格的OnMouseUp事件:

procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  Col, Row: Integer;
begin
  StringGrid1.MouseToCell(X, Y, Col, Row);
  if (Col > -1) and (Row > -1) then
    ShowMessage(ColorToString(TColor(StringGrid1.Objects[Col, Row])));
end;

处理双击然后变得非常简单(感谢@TLama提供大帮助):

procedure TForm1.StringGrid1DblClick(Sender: TObject);
var
  IsDefaultColor: Boolean;
  CurrCellColor: TColor;
  CurrCol, CurrRow: Integer;
begin
  // Save typing by grabbing the currently selected cell col/row
  CurrCol := StringGrid1.Col;   
  CurrRow := StringGrid1.Row;

  // Get the stored color for the selected cell
  CurrCellColor := TColor(StringGrid1.Objects[CurrCol, CurrRow]);

  // See if it's been painted a different color than the default
  IsDefaultColor := (CurrCellColor = StringGrid1.Color);

  if not IsDefaultColor then
    HandleDifferentColorCell
  else
    HandleNormalColorCell;
end;

请注意,如果您选择而不是来更改单元格的颜色,您仍应将单元格的默认颜色指定给Objects[Column, Row],以便在那里有一些有意义的内容为了避免在检索值时出现不正确的转换。

相关问题