如何将对象与TGridColumns对象相关联

时间:2012-02-26 04:51:35

标签: lazarus tstringgrid

我正在跑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;

1 个答案:

答案 0 :(得分: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;
相关问题