C++ Builder XE - 如何实现TFont属性
问题描述:
我正在开发从TCustomControl派生的自定义组件。我想添加新的基于TFont的属性,可以在设计时编辑,例如在TLabel组件中。基本上我想要的是添加用户的选项来更改各种属性的字体(名称,大小,样式,颜色等),而无需将每个属性添加为单独的属性。C++ Builder XE - 如何实现TFont属性
我第一次尝试:
class PACKAGE MyControl : public TCustomControl
{
...
__published:
__property TFont LegendFont = {read=GetLegendFont,write=SetLegendFont};
protected:
TFont __fastcall GetLegendFont();
void __fastcall SetLegendFont(TFont value);
...
}
编译器返回错误 “E2459德尔福样式类必须使用new运算符来构建”。我也不知道我是否应该使用数据类型TFont或TFont *。在我看来,每当用户更改单个属性时,创建新的对象实例效率不高。我将不胜感激代码示例如何完成。
答
从TObject
派生的类必须使用new
运算符在堆上分配。你正在尝试使用TFont
而不使用任何指针,这将无法正常工作。你需要像这样实现你的财产:
class PACKAGE MyControl : public TCustomControl
{
...
__published:
__property TFont* LegendFont = {read=FLegendFont,write=SetLegendFont};
public:
__fastcall MyControl(TComponent *Owner);
__fastcall ~MyControl();
protected:
TFont* FLegendFont;
void __fastcall SetLegendFont(TFont* value);
void __fastcall LegendFontChanged(TObject* Sender);
...
}
__fastcall MyControl::MyControl(TComponent *Owner)
: TCustomControl(Owner)
{
FLegendFont = new TFont;
FLegendFont->OnChange = LegendFontChanged;
}
__fastcall MyControl::~MyControl()
{
delete FLegendFont;
}
void __fastcall MyControl::SetLegendFont(TFont* value)
{
FLegendFont->Assign(value);
}
void __fastcall MyControl::LegendFontChanged(TObject* Sender);
{
Invalidate();
}