OnDrawCell中心文本StringGrid-Delphi [英] OnDrawCell Center Text StringGrid - Delphi

查看:184
本文介绍了OnDrawCell中心文本StringGrid-Delphi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使StringGrid中的文本居中。经过一番研究,我想出了其他人在此处发布的此函数,该函数在DefaultDraw:False上使用时应该起作用。

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;

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

However if I set DefaultDraw:False, the StringGrid just appears glitchey.

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

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和arrby是字符串数组。 sg是StringGrid。

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.

更新

对于那些遭受类似问题困扰的人来说,这段代码是如果if语句

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

该行表示它将仅运行第1列的代码,例如第二列,因为StringGrid基于0。您可以放心地删除if语句,它将在无需禁用默认图形的情况下执行并正常工作。

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.

推荐答案

在我的测试中有效

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;

这篇关于OnDrawCell中心文本StringGrid-Delphi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆