OnMeasureItem (C++)
Description
Here is a typical handler for an OnMeasureItem event. The example assumes that a variable owner-draw list box already has bitmaps associated with each of its strings. It sets the height of the item to the height of the associated bitmap if that height is greater than the default height (ListBox1.ItemHeight). Note that TWinControl can also be used in place of TWidgetControl on Windows.
Code
void __fastcall TForm1::ListBox1MeasureItem(TWinControl *Control, int Index,
int &Height)
{
Graphics::TBitmap *bitmap = dynamic_cast<Graphics::TBitmap *>((dynamic_cast<TListBox *>(Control))->Items->Objects[Index]);
if (bitmap && bitmap->Height > Height)
Height = bitmap->Height;
}
void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int Index,
TRect &Rect, TOwnerDrawState State)
{
Graphics::TBitmap *pBitmap; // Temporary variable for item�s bitmap
int Offset = 2; // Default text offset width
// Note that you draw on the listbox�s canvas, not on the form.
TCanvas *pCanvas = ((TListBox *)Control)->Canvas;
pCanvas->FillRect(Rect); // Clear the rectangle.
pBitmap = dynamic_cast<Graphics::TBitmap *>((dynamic_cast<TListBox *>(Control))->Items->Objects[Index]);
if (pBitmap)
{
pCanvas->BrushCopy(Bounds(Rect.Left + Offset, Rect.Top, pBitmap->Width, pBitmap->Height), pBitmap, Bounds(0, 0, pBitmap->Width, pBitmap->Height), clRed); // render bitmap
Offset += pBitmap->Width + 4; // Add four pixels between bitmap and text.
}
// display the text
pCanvas->TextOut(Rect.Left + Offset, Rect.Top, (dynamic_cast<TListBox *>(Control))->Items->Strings[Index]);
}
#include <memory> //For STL auto_ptr class
Graphics::TBitmap *bitmap0, *bitmap1, *bitmap2;
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
// Making these static keeps them around until the project terminates.
static std::auto_ptr<Graphics::TBitmap> _bitmap0Cleaner(bitmap0 = new Graphics::TBitmap);
static std::auto_ptr<Graphics::TBitmap> _bitmap1Cleaner(bitmap1 = new Graphics::TBitmap);
static std::auto_ptr<Graphics::TBitmap> _bitmap2Cleaner(bitmap2 = new Graphics::TBitmap);
bitmap0->LoadFromFile("../littleB_64.bmp");
// ImageList1->GetBitmap(0, bitmap0);
ListBox1->Items->AddObject("Butterfly", bitmap0);
ImageList1->GetBitmap(3, bitmap1);
ListBox1->Items->AddObject("Animal", bitmap1); // No bitmap; see if it leaves this height at 64.
ImageList1->GetBitmap(4, bitmap2);
ListBox1->Items->AddObject("Sunflower", bitmap2); // No bitmap; see if it leaves this height at 64.
}