delphi - TList 如何从 Frame 的 TEdit/TCombobox 获取输入值
问题描述
主窗体包含TTabControl
可以动态创建一些选项卡。每当我添加一个新选项卡时,都会创建一个框架并将其添加到新选项卡中。最后,我会将所有这些保存TTabItem
到TList
.
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 非常困惑和新手。
解决方案
主要问题是您的框架变量是过程局部变量。
我看到了解决您问题的不同方法。
第一:使用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
,它可以更好,但这取决于你。
推荐阅读
- python-3.x - python中的XlsxWriter在单元格中输入了额外的空格
- firebase - 如何修复 Flutter 中的 firebase_admob 包问题
- javascript - 如何从一组对象过滤一个值创建一个新数组?
- java - 在 JAR 中找不到资源文件
- javascript - “LegendOptions”类型上不存在 Highchart 属性“名称”
- apache - 以哈希模式重定向到 404 页面
- ios - Flutter ios cloud_firestore给出错误
- python-3.x - 将扫描的pdf转换为可读的pdf
- kotlin - 如何启动一个在挂起函数调用者返回后继续运行的协程?
- mysql - 我的 5 分钟间隔查询适用于 5.5.6 版本,但不适用于 5.5.7