Mega Code Archive

 
Categories / Delphi / Graphic
 

Custom Drawing of TListView Items Font, Colors, Graphics

Title: Custom Drawing of TListView Items - Font, Colors, Graphics The TListView Delphi control displays a list of items in a fashion similar to how Windows Explorer displays files and folders. The items can be displayed in columns with column headers and sub-i items, or vertically or horizontally, with small or large icons. If you want to apply custom drawing (fonts, color, graphics) for each individual list item you can simply handle an event or two - and have a list view full of color and visually more attractive elements. Painting Each List Item Individually The OnAdvancedCustomDrawItem event can be used to customize the drawing of individual items on the list view's canvas. The list view receives this event even if the OwnerDraw property is false. The OnAdvancedCustomDrawItem is declared as: procedure(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean) of object Here's a description of the parameters: Sender is the list view whose item is drawn. Item is the item that is currently being painted. State indicates the state of the item, so that the event handler can adjust the image to reflect whether the item is selected, disabled, hot, and so on. Stage indicates the current stage in drawing the list item. Note that the cdPreErase and cdPostErase stages do not receive event notification. The background must be drawn when the item is rendered. DefaultDraw is used only when Stage is cdPrePaint. Set DefaultDraw to false if you don't want the control to paint the item’s text after the event handler exits. If DefaultDraw remains true, the list view adds the item’s text to the image on the canvas. Take a look at the picture: there are 4 items listing a persons name, year and zodiac sign. //handles ListView AdvancedCustomDrawItem procedure TMyForm.ListView1AdvancedCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean) ; var year : integer; sign : string; begin year := StrToInt(item.SubItems[0]) ; sign := item.SubItems[1]; //20th century blue FONT COLOR if year then Sender.Canvas.Font.Color := clBlue else Sender.Canvas.Font.Color := clRed; //bold "aquarius" if sign = 'Aquarius' then Sender.Canvas.Font.Style := Sender.Canvas.Font.Style + [fsBold]; end; (*ListView-AdvancedCustomDrawItem*) Note that the Item (TListItem) parameter has the DisplayRect(Code: TDisplayCode) method which returns the bounding rectangle of the list item. You can use this rectangle if you need to pain some custom graphics onto an item, for example coming from a TImageList control.