OnDrawCell 中心文本 StringGrid - Delphi
我试图让 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 是 StringGrid。
之后我需要执行文本以显示在单元格的中心。
更新
对于那些遇到类似问题的人来说,这段代码的关键问题之一是 if 语句
if ACol = 1 then begin
该行意味着它只会运行第 1 列的代码,例如第二列,因为 StringGrid 是基于 0 的。您可以安全地删除 if 语句,它将执行并工作,而无需禁用默认绘图。
I'm trying to get the text in my StringGrid to center. After some research I came up with this function posted by someone else here that when used on DefaultDraw:False should work.
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;
However if I set DefaultDraw:False, the StringGrid just appears glitchey.
The lines in the function that fill the StringGrid with text is
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 and arrby are arrays of string. sg is the StringGrid.
I need after that has been executing the text to appear in the center on the cell.
UPDATE
For those suffering from similar problems one of the key issues with this piece of code is if the if statement
if ACol = 1 then begin
That line means it will only run the code for column 1 e.g. the second column since StringGrid is 0 based. You can safely remove the if statement and it will execute and work WITHOUT having to disable default drawing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这在我的测试中有效
this works in my test