自删除按钮
我有一个带有一堆tpanels的TSCrollbox,并在运行时生成了一些TBUTTON。 当一个单击一个tbutton时,我需要删除TPANEL,但是在onClick结束时在访问违规中进行此操作...
procedure TMainForm.ButanClick(Sender: TObject);
var
vParentPanel: TPanel;
begin
if (string(TButton(Sender).Name).StartsWith('L')) then
begin
TButton(Sender).Caption := 'YARE YARE DAZE';
end
else
begin
vParentPanel := TPanel(TButton(Sender).GetParentComponent());
TheScrollBox.RemoveComponent(vParentPanel);
vParentPanel.Destroy();
// access violation but the panel is removed
end;
end;
procedure TMainForm.Button3Click(Sender: TObject);
var
i: Integer;
vPanel: TPanel;
vButton: TButton;
begin
for i := 0 to 20 do
begin
vPanel := TPanel.Create(TheScrollBox);
vPanel.Align := alTop;
vPanel.Parent := TheScrollBox;
vButton := TButton.Create(vPanel);
vButton.Align := alLeft;
vButton.Parent := vPanel;
vButton.Name := 'L_butan' + IntToStr(i);
vButton.OnClick := ButanClick;
vButton := TButton.Create(vPanel);
vButton.Align := alRight;
vButton.Parent := vPanel;
vButton.Name := 'R_butan' + IntToStr(i);
vButton.OnClick := ButanClick;
end;
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能从
tbutton
's onClick 事件中安全地销毁父tpanel
(或tbutton
本身)。 VCL仍需要访问tpanel
/tbutton
在事件处理程序退出后进行节拍。因此,您需要将破坏延迟到处理程序退出后。最简单的方法是使用 在tpanel
上调用tobject.free()
,例如:tpanel
将从<<<<<<代码> TSCrollbox 在其破坏过程中。您无需手动处理该步骤。You cannot safely destroy the parent
TPanel
(or theTButton
itself) from inside theTButton
'sOnClick
event. The VCL still needs access to theTPanel
/TButton
for a beat after the event handler exits. So, you need to delay the destruction until after the handler exits. The easiest way to do that is to useTThread.ForceQueue()
to callTObject.Free()
on theTPanel
, eg:The
TPanel
will remove itself from theTScrollBox
during its destruction. You do not need to handle that step manually.用重新解决的schaaf 答案:
Solved with Renate Schaaf answer: