【问题标题】:OnDrawCell Center Text StringGrid - DelphiOnDrawCell 中心文本 StringGrid - Delphi
【发布时间】:2023-04-01 10:49:01
【问题描述】:

我试图让我的 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 语句,它会执行和工作,而无需禁用默认绘图。

【问题讨论】:

  • 我刚刚试过你的代码,它工作正常。 (德尔福 5 和 10 @Win7)
  • 代码的问题在于该过程是针对StringGrid2的,但是在代码中它被列为StringGrid1。我讨厌 delphi 自动完成的另一个原因。但是我认为 Dorin Duminica 的方法更有效。

标签: delphi tstringgrid


【解决方案1】:

这在我的测试中有效

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    相关资源
    最近更新 更多