본문 바로가기

delphi

stringgrid에 체크박스 삽입하는 코드

반응형
SMALL
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
  Grid: TStringGrid;
  CheckBoxRect: TRect;
begin
  Grid := Sender as TStringGrid;

  // Set checkbox for cell in column 2
  if ACol = 2 then
  begin
    CheckBoxRect.Left := Rect.Left + ((Rect.Right - Rect.Left) - 13) div 2;
    CheckBoxRect.Top := Rect.Top + ((Rect.Bottom - Rect.Top) - 13) div 2;
    CheckBoxRect.Right := CheckBoxRect.Left + 13;
    CheckBoxRect.Bottom := CheckBoxRect.Top + 13;
    DrawFrameControl(Grid.Canvas.Handle, CheckBoxRect, DFC_BUTTON, DFCS_BUTTONCHECK or IfThen(Grid.Checked[ACol, ARow], DFCS_CHECKED, 0));
  end
  else
  begin
    // Draw cell contents
    Grid.Canvas.Font := Grid.Font;
    Grid.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, Grid.Cells[ACol, ARow]);
  end;
end;

procedure TForm1.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  Grid: TStringGrid;
  ACol, ARow: Integer;
  CheckBoxRect: TRect;
begin
  Grid := Sender as TStringGrid;
  Grid.MouseToCell(X, Y, ACol, ARow);

  // Toggle checkbox for cell in column 2
  if (Button = mbLeft) and (ACol = 2) then
  begin
    CheckBoxRect.Left := Grid.CellRect(ACol, ARow).Left + ((Grid.CellRect(ACol, ARow).Right - Grid.CellRect(ACol, ARow).Left) - 13) div 2;
    CheckBoxRect.Top := Grid.CellRect(ACol, ARow).Top + ((Grid.CellRect(ACol, ARow).Bottom - Grid.CellRect(ACol, ARow).Top) - 13) div 2;
    CheckBoxRect.Right := CheckBoxRect.Left + 13;
    CheckBoxRect.Bottom := CheckBoxRect.Top + 13;
    if PtInRect(CheckBoxRect, Point(X, Y)) then
    begin
      Grid.Checked[ACol, ARow] := not Grid.Checked[ACol, ARow];
      Grid.InvalidateCell(ACol, ARow);
    end;
  end;
end;
반응형
LIST