2012-04-23 75 views
0

我正在開發從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 *。在我看來,每當用戶更改單個屬性時,創建新的對象實例效率不高。我將不勝感激代碼示例如何完成。

回答

3

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