2

我正在运行 Lazarus 0.9.30。

我在表单上有一个标准的 TStringGrid,并且有一个在运行时动态添加 TGridColumns 对象的函数。我有一个对象集合,其中包含每列的所有属性(我在运行时从文件中读出),并且我想将每个对象与其对应的列标题相关联。

我已经尝试了下面的代码,但是在运行时,当我尝试访问列标题对象后面的对象时,我得到了一个返回的 'nil 对象。我怀疑发生这种情况的原因是网格单元(包含列标题)是空白的,并且您无法将对象与空的网格单元相关联。

type
  TTmColumnTitles = class(TTmCollection)
  public
    constructor Create;
    destructor  Destroy; override;

    function  stGetHint(anIndex : integer) : string;
  end;

type
  TTmColumnTitle = class(TTmObject)
  private
    FCaption         : string;
    FCellWidth       : integer;
    FCellHeight      : integer;
    FFontOrientation : integer;
    FLayout          : TTextLayout;
    FAlignment       : TAlignment;
    FHint            : string;

    procedure vInitialise;

  public
    property stCaption        : string      read FCaption         write FCaption;
    property iCellWidth       : integer     read FCellWidth       write FCellWidth;
    property iCellHeight      : integer     read FCellHeight      write FCellHeight;
    property iFontOrientation : integer     read FFontOrientation write FFontOrientation;
    property Layout           : TTextLayout read FLayout          write FLayout;
    property Alignment        : TAlignment  read FAlignment       write FAlignment;
    property stHint           : string      read FHint            write FHint;

    constructor Create;
    destructor  Destroy; override;
  end;

procedure TTmMainForm.vLoadGridColumnTitles
  (
  aGrid       : TStringGrid;
  aCollection : TTmColumnTitles
  );
var
  GridColumn   : TGridColumn;
  aColumnTitle : TTmColumnTitle; //Just a pointer!
  anIndex1     : integer;
  anIndex2     : integer;
begin
  for anIndex1 := 0 to aCollection.Count - 1 do
    begin
      aColumnTitle := TTmColumnTitle(aCollection.Items[anIndex1]);

      GridColumn := aGrid.Columns.Add;
      GridColumn.Width := aColumnTitle.iCellWidth;
      GridColumn.Title.Font.Orientation := aColumnTitle.iFontOrientation;
      GridColumn.Title.Layout           := aColumnTitle.Layout;
      GridColumn.Title.Alignment        := aColumnTitle.Alignment;
      GridColumn.Title.Caption          := aColumnTitle.stCaption;

      aGrid.RowHeights[0] := aColumnTitle.iCellHeight;
      aGrid.Objects[anIndex1, 0] := aColumnTitle;
    end; {for}
end;
4

1 回答 1

2

仅将对象分配给Objects属性是不够的。您必须自己在事件处理程序中从该对象中绘制标题标题OnDrawCell,或者也分配Cells属性。

并且您不能将对象与空的网格单元相关联

是的你可以。一个单元格的字符串和对象相互独立地“工作”。

所以应该是:

  for anIndex2 := 0 to aGrid.ColCount - 1 do 
  begin
    aColumnTitle := aCollection.Items[anIndex2];   // Is aCollection.Count in sync
                                                   // with aGrid.ColCount??
    aGrid.Cells[anIndex2, 0] := aColumnTitle.Caption;    
    aGrid.Objects[anIndex2, 0] := aColumnTitle;
  end;
于 2012-02-27T10:15:15.233 回答