Skip to main content

TcxCustomCheckListBox.OnDrawItem Event

Occurs when a checklist box item should be repainted.

Declaration

property OnDrawItem: TDrawItemEvent read; write;

Remarks

You can handle the OnDrawItem event to perform custom painting of list box items. This event is called for each list box item. The check list box is passed as the Control parameter. The canvas to perform custom draw can be obtained via the Canvas property of the control’s InnerCheckListBox property.

The item to draw is passed by its index within the Items collection. The area where you can draw is passed as the Rect parameter. The AState parameter provides information on whether the current item is selected, focused, etc.

The following code shows an OnDrawItem handler. Checked items are drawn using bold font. Grayed items are drawn in gray. Check boxes are also painted in a custom manner. For each state, a different bitmap is drawn. A result of custom draw is shown below:

var
  FBmpGrayed, FBmpChecked, FBmpUnchecked: TBitmap;
//...
//Load bitmaps representing item states
procedure TForm1.FormCreate(Sender: TObject);
begin
  FBmpGrayed := TBitmap.Create;
  FBmpGrayed.LoadFromFile('grayed.bmp');
  FBmpChecked := TBitmap.Create;
  FBmpChecked.LoadFromFile('checked.bmp');
  FBmpUnchecked := TBitmap.Create;
  FBmpUnchecked.LoadFromFile('unchecked.bmp');
end;
//Destroy images when disposing of the form
procedure TForm1.FormDestroy(Sender: TObject);
begin
  FBmpGrayed.Free;
  FBmpChecked.Free;
  FBmpUnchecked.Free;
end;
//OnDrawItem event handler
procedure TForm1.cxCheckListBox2DrawItem(Control: TWinControl;
  Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
  ACanvas: TcxCanvas;
  AText: string;
  ATextRect: TRect;
  AGlyphWidth: Integer;
  AListBox: TcxCheckListBox;
  ACheckBmp: TBitmap;
  ACanvasFont: TFont;
  AItemState: TcxCheckBoxState;
  AItemEnabled: Boolean;
begin
  AListBox := (Control as TcxCheckListBox);
  ACanvas := AListBox.InnerCheckListBox.Canvas;
  ACanvasFont := ACanvas.Font;
  AItemState := AListBox.Items[Index].State;
  AItemEnabled := AListBox.Items[Index].Enabled;
  case AItemState of
    cbsUnchecked:
      begin
        ACheckBmp := FBmpUnchecked;
        ACanvasFont.Color := clBlack;
      end;
    cbsChecked:
      begin
        ACheckBmp := FBmpChecked;
        ACanvasFont.Style := [fsBold];
        ACanvasFont.Color := clBlack;
      end;
    cbsGrayed:
      begin
        ACheckBmp := FBmpGrayed;
        ACanvasFont.Color := clGray;
      end;
  end;
  ACanvas.Brush.Color := clWhite;
  ACanvas.FillRect(Rect);
  AGlyphWidth := ACheckBmp.Width;
  ACanvas.DrawGlyph(Rect.Left, Rect.Top, ACheckBmp, AItemEnabled);
  AText := AListBox.Items[Index].Text;
  ATextRect := Rect;
  ATextRect.Left := ATextRect.Left + 3 + AGlyphWidth;
  ACanvas.DrawTexT(AText, ATextRect, 0);
end;
See Also