2

我试图让我的 StringGrid 中的文本居中。经过一些研究,我想出了其他人在这里发布的这个函数,当在 DefaultDraw:False 上使用时应该可以工作。

procedure TForm1.StringGrid2DrawCell(Sender: TObject; ACol, ARow: Integer;
 Rect: TRect; State: TGridDrawState);
var
  S: string;
  SavedAlign: word;
begin
  if ACol = 1 then begin  // ACol is zero based
   S := StringGrid1.Cells[ACol, ARow]; // cell contents
    SavedAlign := SetTextAlign(StringGrid1.Canvas.Handle, TA_CENTER);
    StringGrid1.Canvas.TextRect(Rect,
      Rect.Left + (Rect.Right - Rect.Left) div 2, Rect.Top + 2, S);
    SetTextAlign(StringGrid1.Canvas.Handle, SavedAlign);
  end;
end;

但是,如果我设置 DefaultDraw:False,StringGrid 就会出现故障。

用文本填充 StringGrid 的函数中的行是

Sg.RowCount := Length(arrpos);
for I := 0 to (Length(arrpos) - 1) do
 begin
   sg.Cells[0,i] := arrpos[i];
   sg.Cells[1,i] := arrby[i];
 end;

arrpos 和 arrby 是字符串数组。sg 是字符串网格。

之后我需要执行文本以显示在单元格的中心。

更新

对于那些遭受类似问题的人来说,这段代码的关键问题之一是 if 语句

if ACol = 1 then begin

该行意味着它将仅运行第 1 列的代码,例如,第二列,因为 StringGrid 是基于 0 的。您可以安全地删除 if 语句,它将执行和工作,而无需禁用默认绘图。

4

1 回答 1

6

这在我的测试中有效

procedure TForm1.sgDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
  State: TGridDrawState);
var
  LStrCell: string;
  LRect: TRect;
begin
  LStrCell := sg.Cells[ACol, ARow]; // grab cell text
  sg.Canvas.FillRect(Rect); // clear the cell
  LRect := Rect; 
  LRect.Top := LRect.Top + 3; // adjust top to center vertical
  // draw text
  DrawText(sg.Canvas.Handle, PChar(LStrCell), Length(LStrCell), LRect, DT_CENTER);
end;
于 2011-01-18T06:51:14.863 回答