Use Custom CheckBox Images for a ListView

106 11


When the ViewStyle property of a TListView Delphi control is set to vsReport and CheckBoxes is set to true, list view includes a check box next to the items in the list.

By design this check box is, well, "ugly". It has a nasty thick 2 pixel border - and there's no property to change it.

ListView With "Nice" CheckBoxes

One way to have nice check boxes in a list view control is to use your own custom graphics (16x16 px bitmap image) and draw it over the original check box.
The event to look for is named OnAdvancedCustomDrawItem - it fires even if OwnerDraw is set to false (default).

By handling the OnAdvancedCustomDrawItem event you can customize the drawing of individual items on the list view's canvas (using the Canvas property). OnAdvancedCustomDrawItem occurs at various stages in the rendering of a list item.

To have a nice check box displayed next to the item you can use 2 custom images - one for the checked state and one for the non-checked state.

Have a TImageList with two "check box" images for checked = true and checked = false states.

//listview OnAdvancedCustomDrawItemprocedure TListViewForm.listViewAdvancedCustomDrawItem(   Sender: TCustomListView;   Item: TListItem;   State: TCustomDrawState;   Stage: TCustomDrawStage;   var DefaultDraw: Boolean) ; var   r : TRect; begin   r := item.DisplayRect(drIcon) ;  if stage = cdPostPaint then   if item.Checked then     stateImages.Draw(Sender.Canvas, r.Left - 16, r.Top, 1)   else     stateImages.Draw(Sender.Canvas, r.Left - 16, r.Top, 2) ; end; Unfortunately, the TListView does not raise an event when the "Checked" state changes for a TListItem (an item in the list view).

Here's how to implement the On Item Checked Event for the TListView Control
Note:
1. make sure the ViewStyle property of the list view is set to vsReport. Of course, Checkboxes property must be set to true, also.
2. make sure yu read the Help on AdvancedCustomDrawItem event - to make familiar with Stages, States, DisplayRect etc.

procedure TListViewForm.FormCreate(Sender: TObject) ; begin   listView.Checkboxes := true;   listView.ViewStyle := vsReport; end; That's it. Tricky but powerful.
Delphi tips navigator:
» Take a Screen Shot of an Inactive Window - Using PrintWindow API and Delphi
« No Main Form Delphi Application

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.