Skip to main content

Custom Painting

  • 2 minutes to read

Both tab and page controls enable you to custom paint tabs. This topic describes the ways in which to do so.

First, you will need to set the OwnerDraw property to True to enable tab custom painting then handle the OnDrawTab event which fires for each tab within the control every time it needs to be repainted.

The code below represents an OnDrawTab event handler. It fills the background of tabs with a texture brush. The ‘texture.bmp’ file for used to initialize the brush must reside in the same folder as the project. A blue rectangle is painted around the main tab. The caption of the main tab is painted using a bold font.

procedure TForm1.cxTabControl1DrawTab(AControl: TcxCustomTabControl;
  ATab: TcxTab; var DefaultDraw: Boolean);
var
  R: TRect;
  Bitmap: TBitmap;
  ABrush: TBrush;
begin
  // creating a brush
  Bitmap := TBitmap.Create;
  Bitmap.LoadFromFile('texture.bmp');
  ABrush := TBrush.Create;
  ABrush.Bitmap := Bitmap;
  with AControl.Canvas do
  begin
    R := ATab.VisibleRect;
    // painting the focus rectangle
    if ATab.IsMainTab then
    begin
      FrameRect(R, clBlue);
      InflateRect(R, -1, -1);
      FrameRect(R, clBlue);
      InflateRect(R, -1, -1);
    end;
    // painting the background
    Windows.FillRect(Handle, R, ABrush.Handle);
    // painting the tab caption
    Font.Color := clBlack;
    if ATab.IsMainTab then
      Font.Style := [fsBold];
    Brush.Style := bsClear;
    DrawText(ATab.Caption, R, cxAlignHCenter);
    Brush.Style := bsSolid;
    Font.Style := [];
  end;
  Bitmap.Free;
  ABrush.Free;
  // prohibiting default painting
  DefaultDraw := False;
end;

Execution of the code listed above will appear as follows:

You can also use a more simple technique to customize the appearance of individual tabs. The OnDrawTabEx event enables you to change the font applied to each individual tab caption. Note that this event also fires only if the OwnerDraw property value is True.

The following code is the handler of the OnDrawTabEx event. It is used to display the active page’s tab using a bold font.

procedure TForm1.cxTabControl1DrawTabEx(AControl: TcxCustomTabControl;
  ATab: TcxTab; Font: TFont);
begin
  if ATab.IsMainTab then
    Font.Style := [fsBold];
end;

Execution of the code listed above will appear as follows: