首页 > 解决方案 > TList 如何从 Frame 的 TEdit/TCombobox 获取输入值

问题描述

主窗体包含TTabControl可以动态创建一些选项卡。每当我添加一个新选项卡时,都会创建一个框架并将其添加到新选项卡中。最后,我会将所有这些保存TTabItemTList.

TForm1 = class(TForm)
  TabControl1: TTabControl;

procedure TForm1.AddNewTab;
var
  profileFrame :TProfileFrame;
begin
  profileFrame := TProfileFrame.Create(Self);

  //TabItem
  TabItem := TabControl1.Add();
  inc(tab_name_Count);
  tabItem.Text := tab_name_Count.ToString;
  //
  profileFrame.Parent := tabItem;
  tablist.Add(TabItem);
end;

这是我的框架:

TProfileFrame = class(TFrame)
 Name: TEdit;
 Gender: TComboBox;

最后,如何获取框架中的(姓名)和(性别)值,并以主窗体打印出来?如果假设我创建了 4 个选项卡,每个选项卡都有自己的框架,我怎样才能从不同的框架中获取值?我对 Delphi 非常困惑和新手。

标签: delphiframefiremonkeytabcontroltlist

解决方案


主要问题是您的框架变量是过程局部变量。

我看到了解决您问题的不同方法。

第一:使用TObjectList

uses ..., System.Generics.Collections;

TForm1 = class(TForm)
  TabControl1: TTabControl;
private
  FFrames:TObjectList<TProfileFrame>;    

procedure TForm1.AddNewTab;
var
  profileFrame :TProfileFrame;
begin
  //TabItem
  TabItem := TabControl1.Add();
  profileFrame := TProfileFrame.Create(TabItem); 
  inc(tab_name_Count);
  tabItem.Text := tab_name_Count.ToString;
  profileFrame.Parent := tabItem;
  if not assigned(FFrames) then
    FFrames := TObjectList<TProfileFrame>.Create(false); //we don't need ObjectList to own Frame, I suppose, so we have to pass `false` into Create method
  FFrames.Add(profileFrame);
  tablist.Add(TabItem);
end;

//Just to demonstrate how to get value from frame
function TForm1.GetGenderFromFrame(ATabItem:TTabItem):String;
var i:integer;
begin
  result := '';
  if FFrames.Count > 0 then
  for i := 0 to FFrames.Count - 1 do
    if FFrames[i].TabItem = ATabItem then
    result := FFrames[i].Gender.Selected.Text;
end;

或者您可以使用另一种方式(在 Delphi 10.1 FMX Project 上进行检查)。您必须像这样更改您的程序:

procedure TForm1.AddNewTab;
var
  profileFrame :TProfileFrame;
begin  
  //TabItem
  TabItem := TabControl1.Add();
  profileFrame := TProfileFrame.Create(TabItem);
  inc(tab_name_Count);
  tabItem.Text := tab_name_Count.ToString;
  //
  profileFrame.Parent := tabItem;
  tablist.Add(TabItem);
end;

现在你的框架有所有者:TabItem。并且TabItem有组件。我们可以使用它:

function TForm1.GetGenderFromFrame(ATabItem:TTabItem):String;
var i:integer;
begin
  result := '';
  if ATabItem.ComponentCount > 0 then
  for i := 0 to ATabItem.ComponentCount - 1 do
    if ATabItem.Components[i] is TProfileFrame then
    result := (ATabItem.Components[i] as TProfileFrame).Gender.Selected.Text;
end;

PS你可以使用for ... in ... do代替for ... to ... do,它可以更好,但这取决于你。


推荐阅读