gpt4 book ai didi

delphi - 析构函数中的 TComboBox 'Control has no parent window'

转载 作者:行者123 更新时间:2023-12-03 15:30:40 26 4
gpt4 key购买 nike

我正在使用Delphi XE2。我构建了一个自定义 TComboBox,以便可以轻松添加键/字符串对并处理组件析构函数中的清理工作。

全部 如果不是(ComponentState 中的 csDesigning) 为简洁起见,省略了代码。

interface

type
TKeyRec = class(TObject)
Key: string;
Value: string;
end;

TMyComboBox = class(TComboBox)
public
destructor Destroy; override;
procedure AddItemPair(const Key, Value: string);
end;

implementation

destructor TMyComboBox.Destroy;
var i: Integer;
begin
for i := 0 to Self.Items.Count - 1 do
Self.Items.Objects[i].Free;
Self.Clear;
inherited;
end;

procedure TMyComboBox.AddItemPair(const Key, Value: string);
var rec: TKeyRec;
begin
rec := TKeyRec.Create;
rec.Key := Key;
rec.Value := Value;
Self.Items.AddObject(Value, rec);
end;

当应用程序关闭时,析构函数被调用,但 Items.Count 属性不可访问,因为 TComboBox 必须有父控件才能访问此属性。当析构函数被调用时,它不再具有父控件。

我以前见过这个问题一次,必须将对象存储在单独的 TList 中并单独释放它们。但这之所以有效,是因为我将它们添加到 TList 的顺序始终与添加到组合框的字符串相同。当用户选择一个字符串时,我可以使用组合框索引在 TList 中查找相关对象。如果组合框已排序,则索引将不匹配,因此我不能总是使用该解决方案。

还有人看过这个吗?您是如何解决这个问题的?如果能够在组件的析构函数中释放对象,那就太好了!

最佳答案

您可以重写函数GetItemsClass:

function GetItemsClass: TCustomComboBoxStringsClass; override;

它由 Combo 调用来创建项目(默认情况下它可能是 TComboBoxStrings )。然后您可以创建自己的 TComboBoxStrings 后代,例如 TComboBoxStringObjects,其中您可以释放与项目链接的对象(当项目被删除时)。

关于delphi - 析构函数中的 TComboBox 'Control has no parent window',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com