Question

I am developing custom component derived from TCustomControl class. I would like to add new TFont based property that could be edited in design-time like for example in TLabel component. Basically what I want is to add user the option to change various atttributes of font (name, size, style, color and so on) without adding each of these attributes as separate property.

My first attempt:

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

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

Compiler returns error "E2459 Delphi style classes must be constructed using operator new". I also don't know if I should use data type TFont or TFont*. It seems to me inefficient to create new object instance every time user change single attribute. I would appreciate code sample how can this be accomplished.

Was it helpful?

Solution

Classes derived from TObject must be allocated on the heap using the new operator. You are trying to use TFont without using any pointers, which will not work. You need to implement your property like this:

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top