Search code examples
delphicombobox

ComboBox On DrawItem doesn't work with hover


I want the comboBox Item to change color if the object associated has a certain value. I did the following:

with Control as TComboBox do
  begin
     Canvas.Font.Color:=clBlack;
     Canvas.Brush.Color := clWhite ;
     if TMyObj(MyCb.Items.Objects[MyCb.ItemIndex]).C = 'C' then
        Canvas.Brush.Color := clred ;
     Canvas.FillRect(Rect);
     Canvas.TextOut(Rect.Left, Rect.Top, Items[Index])
 end;

I can see all of the Combo items black on White. When I hover with the mouse, all of the items on which I hover are painted red (even if the C value is not 'C'

Do you understand why?


Solution

  • Yes. You're repeatedly setting the color based on the ItemIndex, which does not change during the drawing of the item. You should be using the Index provided when the method is called as one of the parameters.

    with Control as TComboBox do
    begin
      Canvas.Font.Color := clBlack;
      Canvas.Brush.Color := clWhite ;
      if TMyObj(Control.Items.Objects[Index]).C = 'C' then // Change this line
        Canvas.Brush.Color := clred ;
      Canvas.FillRect(Rect);
      Canvas.TextOut(Rect.Left, Rect.Top, Items[Index])
    end;