【问题标题】:Custom button inherited from TButton does not show从 TButton 继承的自定义按钮不显示
【发布时间】:2014-11-09 23:05:57
【问题描述】:

我正在将一个大型项目转换为 Firemonkey,我们有一些自定义按钮,这些按钮未显示在表单上。我已将问题隔离到一个非常简单的项目:

使用下面的代码,在移动和桌面上(使用 Delphi XE6 中的默认新应用程序),创建 tTestButton1 可以正常工作,但 tTestButton2 不会显示在表单上。这怎么可能?

type
tTestButton1 = class(TButton);
tTestButton2 = class(tTestButton1);

tMainForm = class(TForm)
private
  fTestButton: TButton;
public
  constructor Create(aOwner: TComponent); override;
end;

constructor tMainForm .Create(aOwner: TComponent);
begin
  inherited;

//  fTestButton := tTestButton1.Create(Self); // this works fine (used instead of next line)
  fTestButton := tTestButton2.Create(Self);  //this button does not show up
  fTestButton.Text := 'Test';
  fTestButton.Parent := Self;
  fTestButton.Visible := True;
  fTestButton.Position.X := 20;
  fTestButton.Position.Y := 20;
end;

【问题讨论】:

  • +1 个很好的问题,很棒的重现代码,要是他们都这么好就好了
  • 可以在 Delphi XE3 中重现。
  • 这是设计使然。视觉组件必须注册样式。否则不会显示。在内部,编译器只查找第一个派生类。
  • @DavidHeffernan,在第一个例子中可以找到ButtonStyle,但在没有注册TestButton1Style的第二个例子中找不到。
  • @DavidHeffernan,在这里讨论,codeverge.com/embarcadero.delphi.firemonkey/…

标签: delphi firemonkey delphi-xe6


【解决方案1】:

问题是控件没有注册样式。所以自然的解决方案是让你这样做。

但这是一个合理的工作量,我希望您真正想做的只是安排控件使用与TButton 相同的样式。像这样实现:

type
  TButtonBase = class(TButton)
  protected
    function GetDefaultStyleLookupName: string; override;
  end;

function TButtonBase.GetDefaultStyleLookupName: string;
begin
  Result := 'Buttonstyle';
end;

现在从TButtonBase 派生您的类。

type
  tTestButton1 = class(TButtonBase);
  tTestButton2 = class(tTestButton1);

TButtonBase派生的类将使用名为Buttonstyle的样式,而不是根据控件的类名查找样式。

【讨论】:

  • 在实际代码中,我现在在“tTestButton1”的构造函数中设置了 StyleLookup,这两个类现在都显示为表单上的按钮。当有一个简单的问题解决方案时很好:-)
  • @Hans 这正是我的建议。我插入了一个额外的类TButtonBase,如果您愿意的话,可以为您提供派生其他按钮类的空间。但也许tTestButton1 已经是那个基类了。我很感激您为了提出问题而将真实代码简化为一个小而简单的复制品。再一次,我不能高度赞扬你这样做。
  • 一个更优雅的解决方案是重写 DefaultStyleLookupName 方法以返回 'ButtonStyle'。
  • @Mike 我相信你是对的。你能解释一下为什么这样更优雅吗?
  • @Mike OK。我想我明白为什么了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
相关资源
最近更新 更多