“控制没有父”中创建ComboBox [英] "Control has no parent" in Create ComboBox
问题描述
在此代码中:
unit MSEC;
interface
uses
Winapi.Windows, Vcl.Dialogs, Vcl.ExtCtrls, System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls;
type
TMSEC = class(TWinControl)
private
FOpr :TComboBox;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
const
DEF_OPERATIONS :array[0..3] of Char = ('+', '-', '*', '/');
constructor TMSEC.Create(AOwner: TComponent);
var i :Integer;
begin
inherited;
FOpr:= TComboBox.Create(Self);
with FOpr do begin
Parent:= Self;
Align:= alLeft;
Width:= DEF_OPERATIONS_WIDTH;
Style:= csDropDownList;
//error in next lines :
Items.Clear;
for i := Low(DEF_OPERATIONS) to High(DEF_OPERATIONS) do Items.Add(DEF_OPERATIONS[i]);
ItemIndex:= 0;
end;
end;
end.
当我更改ComboBox项目时,程序中断并显示以下消息:
<
如何解决此错误或以另一种方式初始化ComboBox项?
When I change ComboBox items, the program breaks with the message :
'Control' has no parent.
How can I fix this error or initialize ComboBox items in another way?
推荐答案
TComboBox
需要分配的HWND才能在其 Items
属性中存储字符串。为了 TComboBox
获得一个HWND,它的 Parent
需要一个HWND,其父
需要HWND,以此类推。问题是你的 TMSEC
对象在其构造函数运行时没有分配 Parent
,因此不可能 TComboBox
取得HWND,请输入错误。
TComboBox
requires an allocated HWND in order to store strings in its Items
property. In order for TComboBox
to get an HWND, its Parent
needs an HWND first, and its Parent
needs an HWND, and so on. The problem is that your TMSEC
object does not have a Parent
assigned yet when its constructor runs, so it is not possible for the TComboBox
to get an HWND, hense the error.
请尝试:
type
TMSEC = class(TWinControl)
private
FOpr: TComboBox;
protected
procedure CreateWnd; override;
public
constructor Create(AOwner: TComponent); override;
end;
constructor TMSEC.Create(AOwner: TComponent);
begin
inherited;
FOpr := TComboBox.Create(Self);
with FOpr do begin
Parent := Self;
Align := alLeft;
Width := DEF_OPERATIONS_WIDTH;
Style := csDropDownList;
Tag := 1;
end;
end;
procedure TMSEC.CreateWnd;
var
i :Integer;
begin
inherited;
if FOpr.Tag = 1 then
begin
FOpr.Tag := 0;
for i := Low(DEF_OPERATIONS) to High(DEF_OPERATIONS) do
FOpr.Items.Add(DEF_OPERATIONS[i]);
FOpr.ItemIndex := 0;
end;
end;
这篇关于“控制没有父”中创建ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!