我正试图把我的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设置为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是StringGrid。
我需要在此之后执行文本,使其出现在单元格的中心。
更新
对于那些患有类似问题的人,这段代码的关键问题之一是if语句
if ACol = 1 then begin这一行意味着它将只运行第1列的代码,例如第二列,因为StringGrid是基于0的。您可以安全地删除if语句,它将执行并工作,而不必禁用默认绘图。
发布于 2011-01-18 06:51:14
这在我的测试中有效。
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;https://stackoverflow.com/questions/4720255
复制相似问题