"创建组合框"中的"控件没有父级"

Moh*_*enB 0 delphi components 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.
Run Code Online (Sandbox Code Playgroud)

当我更改ComboBox项目时,程序会中断消息:
'Control'没有父项.
如何修复此错误或以其他方式初始化ComboBox项?

Rem*_*eau 8

TComboBox需要一个已分配的HWND才能在其Items属性中存储字符串.为了TComboBox获得HWND,它Parent首先Parent需要HWND,并且需要HWND,依此类推.问题是你的TMSEC对象Parent在其构造函数运行时还没有分配,所以不可能TComboBox获得HWND,而是错误.

试试这个:

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;
Run Code Online (Sandbox Code Playgroud)