gpt4 book ai didi

delphi - 为什么我的运行时创建的组件没有出现在表单上?

转载 作者:行者123 更新时间:2023-12-03 15:22:14 24 4
gpt4 key购买 nike

我正在测试来自此问答 Component Creation - Joining Components Together? 的示例了解如何创建自定义/复合组件。

虽然示例中安装的组件可以拖到表单上,但我似乎无法在运行时创建它。

procedure TForm1.Button1Click(Sender: TObject);
var
MyPanel2 : TMyPanel;
begin
MyPanel2 := TMyPanel.Create(Form1);
With MyPanel2 do
begin
Left := 10;
Top := 10;
Width := 400;
Height := 400;
Visible := True;
Image.Picture.LoadFromFile('C:\test.png');
end;
end;

我尝试了 self 和 Form1 作为所有者。使用面板和图像的属性。

只是不确定我做错了什么。没有错误,除非我忘记将 pngimage 添加到我的使用中。很好地单步执行代码,运行时创建在视觉上没有发生任何事情。

最佳答案

您需要设置Parent在运行时代码中。

MyPanel2 := TMyPanel.Create(Self);
with MyPanel2 do
begin
Parent := Self;//oops, you forgot to set this
SetBounds(10, 10, 400, 400);
Image.Picture.LoadFromFile('C:\test.png');
end;

您问题中的代码不会导致控件显示为普通的 TPanel,或者实际上任何控件。

来自documentation ,我强调的是:

Specifies the parent of the control.

Use the Parent property to get or set the parent of the control. The parent of a control is the control that contains it. For example, if an application includes three radio buttons in a group box, the group box is the parent of the three radio buttons, and the radio buttons are the child controls of the group box.

To serve as a parent, a control must be an instance of a TWinControl descendant.

When creating a new control at run time, assign a Parent property value for the new control. Usually, this is a form, panel, group box, or a control that is designed to contain another. Changing the parent of a control moves the control onscreen so that it is displayed within the new parent. When the parent control moves, the child moves with the parent.

关于delphi - 为什么我的运行时创建的组件没有出现在表单上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14570742/

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