OnDrawCell Center Text StringGrid - Delphi

≡放荡痞女 提交于 2020-01-02 10:33:12

问题


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.


回答1:


this works in my test

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/ondrawcell-center-text-stringgrid-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!