【问题标题】:C++ Builder XE - How to implement TFont propertyC++ Builder XE - 如何实现 TFont 属性
【发布时间】:2012-04-23 13:31:30
【问题描述】:

我正在开发从 TCustomControl 类派生的自定义组件。我想添加新的基于 TFont 的属性,可以在设计时编辑,例如在 TLabel 组件中。基本上我想要的是向用户添加更改字体的各种属性(名称、大小、样式、颜色等)的选项,而无需将这些属性中的每一个都添加为单独的属性。

我的第一次尝试:

class PACKAGE MyControl : public TCustomControl
{
...
__published:
    __property TFont LegendFont = {read=GetLegendFont,write=SetLegendFont};

protected:
    TFont __fastcall GetLegendFont();
    void __fastcall SetLegendFont(TFont value);
...
}

编译器返回错误“E2459 Delphi 样式类必须使用 operator new 构造”。我也不知道我应该使用数据类型 TFont 还是 TFont*。在我看来,每次用户更改单个属性时创建新的对象实例效率低下。我将不胜感激代码示例如何实现这一点。

【问题讨论】:

    标签: properties fonts custom-component c++builder-xe


    【解决方案1】:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      相关资源
      最近更新 更多