Delphi,在不同的TGridPanelLayout单元格中显示按钮

时间:2015-02-20 01:01:54

标签: delphi firemonkey delphi-xe6 gridpanel controlcollection

您好我正在使用XE6,我正在使用一个带有4列和4行的TGridPanelLayout。在第一个单元格中,我正在显示一个Button。我想要做的是,当我点击这个按钮时,让该按钮出现在不同的单元格中。但我找不到怎么做,到目前为止我试过这个,但没有任何反应。

procedure TForm4.Button1Click(Sender: TObject);
begin
GridMyPannel.ControlCollection.BeginUpdate;
GridMyPannel.ControlCollection.AddControl(Button1, 2, 2);
Button1.Parent := GridMyPannel;
end;

我是德尔福的新手。谁能给我一个如何做到这一点的例子?

2 个答案:

答案 0 :(得分:1)

TGridPanel具有ControlCollection属性,允许您访问RowColumn属性,这些属性也会在您TButton上显示放在TGridpanel内。 TButton(或更确切地说,其超类TControl)没有RowColumn属性。因此,我们需要掌握TControlItem使用的TGridpanel包装器。

procedure TForm8.Button1Click(Sender: TObject);
var
    selectedControl:        TControl;
    itemIndex:              Integer;
    selectedControlItem:    TControlItem; // This knows about "Row" and "Column"
begin
    // This is the button we've clicked
    selectedControl := Sender as TControl;

    itemIndex := GridPanel1.ControlCollection.IndexOf(selectedControl);
    if (itemIndex <> -1) then begin
        selectedControlItem := GridPanel1.ControlCollection.Items[itemIndex];
        selectedControlItem.Row := Random(GridPanel1.RowCollection.Count);
        selectedControlItem.Column := Random(GridPanel1.ColumnCollection.Count);
    end;
end;

上面的代码找到按钮并将其RowColumn属性更改为随机值。请注意,您没有指定TButton是否是TGridpanel中唯一的控件。是这样的吗?

答案 1 :(得分:0)

我在普通VCL和XE3以及TGridPanel(我的Delphi中没有TGridPanelLayout)中执行了以下操作。

GridPanel的问题在于它不允许将控件(按钮等)放置在任何单元格(如Cell:1,1)中,而不在该单元格之前的单元格中进行控制。 GridPanel总是从索引0向上填充。

所以诀窍是愚弄它。现在,根据你是否已经在GridPanel中有其他单元格,如果按钮位于较低索引的单元格中,则必须为该按钮设置位置并在其位置放置其他内容。

在按下按钮之前查看表单:

enter image description here

请注意,我还没有在单元格1,0创建一个ControlItem。

我想将Button 1移动到单元格1,0。除非我先在其位置放置其他东西(单元格0,0),否则我不能这样做。我必须在单元格1,0创建一个新的ControlItem来容纳button1。

procedure TForm1.Button1Click(Sender: TObject);
begin
  // Places CheckBox1 in the same cell as BUtton1
  GridPanel1.ControlCollection.ControlItems[0,0].Control := CheckBox1;
  // Create a new ControlItem for Button1 and in the same breath move
  // Button1 to it
  GridPanel1.ControlCollection.AddControl(Button1,1,0);
  // You know what this does. :)
  CheckBox1.Parent := GridPanel1;
end;

结果:

enter image description here