Dakoy
Dakoy

Reputation: 53

How to make a groupbox's background transparent?

How to set Groupbox to transparent? I found this Transparent, But in my case, I put TImage and put a background image, then the Groupbox, I don't know how can I make the groupbox transparent, and show the image as a background.

I tried searching this on google, but can't find the answer, and as much as possible, i want to use VCL Application.

Upvotes: 1

Views: 2599

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

I think you'll need to take over painting the group box. Here's a simple example using an interposer class. Place this class in the same unit as your form, before your form is declared:

type
  TGroupBox = class(StdCtrls.TGroupBox)
  protected
    procedure Paint; override;
  end;

  TForm1 = class(TForm)
    GroupBox1: TGroupBox;
    ....
  end;

....

procedure TGroupBox.Paint;
begin
  Canvas.Draw(0, 0, SomeGraphicObjectContainingYourBackground);
  inherited;
end;

The output looks like this:

enter image description here

You may want to customise the rest of the painting. Perhaps it's enough to draw the background inside the group box so that the caption and frame appear as normal. Specify different coordinates in the call to Canvas.Draw if you want that. If you need the background to cover the entire parent canvas then your call to Draw needs to pass -Left and -Top for the coordinates.

Or perhaps you want to take over the drawing of the frame. Do that by not calling the inherited Paint method and doing your own work.

To avoid flicker, you are actually best off moving this painting code into WM_ERASEBKGND. That makes things a little more complex, but not much. The code would look like this:

type
  TGroupBox = class(StdCtrls.TGroupBox)
  protected
    procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
  end;

procedure TGroupBox.WMEraseBkgnd(var Message: TWmEraseBkgnd);
begin
  Canvas.Handle := Message.DC;
  try
    Canvas.Draw(-Left, -Top, SomeGraphicObjectContainingYourBackground);
  finally
    Canvas.Handle := 0;
  end;
  Message.Result := 1;
end;

If you were going to do this properly, you'd want to make a proper component rather than hacking around with an interposer.

Upvotes: 4

Related Questions