在表单上,​​我放下了1个TCategoryPanelGroup对象,并添加了3个TCategoryPanel。在例程中,我需要遍历每个TCategoryPanel并遍历每个对象到那些面板上以产生输出。

因此,这是代码...为什么要在第二个FOR中而不是给我每个组件的类名(即TButtonTLabel等),而是给出一个TCategoryPanelSurface

简短的问题:如何从每个TCategoryPanel访问每个控件?



procedure TForm1.Button2Click(Sender: TObject);
    var i,i2 : integer;

    begin
      for i := 0 to CategoryPanelGroup1.ControlCount-1 do
      begin
        showMessage((CategoryPanelGroup1.Controls[i] as TCategoryPanel).caption ) ;

        for i2 := 0 to (CategoryPanelGroup1.Controls[i] as TCategoryPanel).ControlCount-1 do
        begin

          showMessage((CategoryPanelGroup1.Controls[i] as TCategoryPanel).Controls[i2].ClassName);
        end;
      end;
    end;

最佳答案

您应该遍历组的基础TWinControl.Controls[]列表,而应该遍历其TCategoryPanelGroup.Panels列表。

至于为什么看到TCategoryPanelSurface出现的原因,TCategoryPanel将该对象创建为其自身的直接子代,并在其构造函数中创建。此后放置到面板中的任何控件实际上都是该TCategoryPanelSurface对象的子级,而不是TCategoryPanel本身的子级。这就是为什么循环永远看不到那些控件的原因。

不幸的是,TCategoryPanel不能公开直接访问其TCategoryPanelSurface对象。因此,为了遍历其子级,您必须首先能够访问它。有两种可能的方法:

1)

procedure TForm1.Button2Click(Sender: TObject);
var
  i, j: integer;
  panel: TCategoryPanel;
  surface: TCategoryPanelSurface;
begin
  for i := 0 to CategoryPanelGroup1.Panels.Count-1 do
  begin
    panel := TCategoryPanel(CategoryPanelGroup1.Panels[i]);
    ShowMessage(panel.Caption);
    surface := panel.Controls[0] as TCategoryPanelSurface;
    for j := 0 to surface.ControlCount-1 do
    begin
      ShowMessage(surface.Controls[j].ClassName);
    end;
  end;
end;


2)

type
  TCategoryPanelAccess = class(TCategoryPanelAccess)
  end;

procedure TForm1.Button2Click(Sender: TObject);
var
  i, j: integer;
  panel: TCategoryPanel;
  surface: TCategoryPanelSurface;
begin
  for i := 0 to CategoryPanelGroup1.Panels.Count-1 do
  begin
    panel := TCategoryPanel(CategoryPanelGroup1.Panels[i]);
    ShowMessage(panel.Caption);
    surface := TCategoryPanelAccess(panel).FPanelSurface;
    for j := 0 to surface.ControlCount-1 do
    begin
      ShowMessage(surface.Controls[j].ClassName);
    end;
  end;
end;

10-05 22:41