好的,我正在尝试在TScrollBox表面上创建一些自定义数量的TPanel,就像你可以在下面的图像上看到的那样。
为了得到这个,我正在使用以下代码,并且工作正常。
var
pan: array of TPanel;
maxp, i, x, y: Integer;
...
maxp := 10;
SetLength(pan, maxp);
for i := 1 to maxp do begin
// x is correct value; doesn't cause problem
// y is correct value; doesn't cause problem
pan[i-1] := TPanel.Create(form1);
with pan[i-1] do begin
Width := 100;
Height := 150;
Top := x * 151;
Left := y * 101;
Parent := ScrollBox1;
end;
end;
现在,我有问题将TImage对象放在每个具有相同索引的TPanel中(img [0] - > pan [0],img [1] - > pan [1]等)。请看下图:
使用相同的逻辑,我试图创建TImage,但没有成功。
我正在使用此代码,无法弄清楚是什么问题。它对我来说看起来很简单,但不知怎的,它没有提供预期的效果。
var
pan: array of TPanel;
img: array of TImage;
maxp, i, x, y: Integer;
...
maxp := 10;
SetLength(pan, maxp);
SetLength(img, maxp);
for i := 1 to maxp do begin
// x is correct value; doesn't cause problem
// y is correct value; doesn't cause problem
pan[i-1] := TPanel.Create(form1);
with pan[i-1] do begin
Width := 100;
Height := 150;
Top := x * 151;
Left := y * 101;
Parent := ScrollBox1;
end;
img[i-1] := TImage.Create(form1);
with img[i-1] do begin
Width := 98;
Left := 1;
Height := 148;
Top := 1;
// in original code next line had img[0]. which caused problem
Picture.LoadFromFile('some_image_file');
Parent := pan[i-1];
end;
end;
不知何故,它将所有TImage对象放在第一个TPanel(pan [0])中的相同位置。这对我来说很困惑,因为它说Parent := pan[i-1];
但是由于某种原因它总是把TImage放在pan [0]中。我尝试使用断点来查看每个for循环周期后发生了什么(最后添加了Application.ProcessMessages),它确实创建了10个不同的图像但是将它们放到了pan [0]上。当然,最后它只显示加载到pan [0]中的最后一个图像。
我的问题是如何为每个动态TPanel制作一个动态TImage(具有相同的数组索引)?
解决!
答案 0 :(得分:5)
建议 - 摆脱with
块。起初它们看似无辜和简单,但从长远来看,它们只能编写难以排除故障的草率代码。如果您一直使用显式变量引用,那么首先就不会发生这个问题。
var
Panels: array of TPanel;
Panel: TPanel;
Images: array of TImage;
Image: TImage;
maxp, i, x, y: Integer;
...
maxp := 10;
SetLength(Panels, maxp);
SetLength(Images, maxp);
for i := 1 to maxp do begin
Panel := TPanel.Create(form1);
Panels[i-1] := Panel;
Panel.Parent := ScrollBox1;
Panel.SetBounds(...);
Image := TImage.Create(form1);
Images[i-1] := Image;
Image.Parent := Panel;
Image.SetBounds(...);
Image.Picture.LoadFromFile('some_image_file');
end;
答案 1 :(得分:2)
您设置了Height
两次而没有设置Left
,所以看起来好像。
with pan[i-1] do begin
Width := 100;
Height := 150;
Top := x * 151;
Height := y * 101;
Parent := ScrollBox1;
end;
答案 2 :(得分:1)
要在delphi中自动完成,我在img[0]
前面使用了Picture.LoadFromFile()
。然后,显然我忘了从代码中删除它,并且从小时前那个'前缀'停留在那里使所有图像加载到相同的img [0]。我确信Parent或Pos / Size属性有问题,并且一直关注这个事情并不关心这个问题。
我实际上已经
了 with img[i-1] do begin
Width := 98;
Left := 1;
Height := 148;
Top := 1;
img[0].Picture.LoadFromFile('some_image_file');
Parent := pan[i-1];
end;
但不知怎的,我在发布这个问题时删除了那个img [0]部分,并且在我的Delphi代码中没有看到它的问题。显然,当我格式化这段代码时,我删除了一些部分,这使得回答我的问题变得不可能:(
真的很抱歉打扰你们,这是我的坏事。