Don’t expect the Parent property to be set inside an FMX control’s Paint method

So… I’m working on a little custom FireMonkey control. As in the VCL, if you want to handle drawing a custom control yourself, you need to override its Paint method. In my case the override was looking like this:

procedure TMyChildControl.Paint;
  if (Parent <> nil) and (Parent.Parent is TMyOtherControl) then
  Canvas.FillText(LocalRect, SomeText, False, 1, [], TTextAlign.taCenter);

If you’re wondering, this was partly a workaround for the fact FMX doesn’t have a ‘parent font’ concept like the VCL. Anyhow, the code seemed to work fine until I enabled drag and drop. In FireMonkey, the drag image for an internal drag and drop operation is dynamically created from the image of the dragged control (good), but in my case, the drag image wasn’t being drawn with the proper font set. Digging through the source I discovered the reason: BeginAutoDrag calls MakeScreenshot to generate the drag image, which calls PaintTo… whose final parameter is a parent property override that defaults to nil. As such, while my Paint override was being called, the Parent property was returning nil inside of it. Argh…


2 thoughts on “Don’t expect the Parent property to be set inside an FMX control’s Paint method

  1. Expect it to be set in the SetParent() Setter…just a guess…
    Oh…you can override AddChild() or RemoveChild() too IIRC.

    • So… instead of just relying on a property not lying about what its value actually is, you should trap the ancestor class’ property setter and maintain a second property (‘RealParent’)…?

      In this particular case, my guess is the author used a default parameter value as a shortcut for implementing an overload (I’ve done it myself…). The problem is, the caller has to be aware that the default behaviour is in fact special behaviour (here, to temporarily override the real value of the Parent propery), which is bad design.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s