ListBox with Items in several colors  

Send By: Q3 Team
Web : http://www.q3.nu
Email: dlib@q3.nu
Date: 29/08/20

Tip accessed 649 times

 


  • Simply put their Style property to lbOwnerDrawFixed and put the next code in their OnDrawItem event:



     procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
       Rect: TRect; State: TOwnerDrawState);
     begin
       with (Control as TListBox) do
       begin
         {The Odd Items in Red, the others in black}
         {Los Items pares de color rojo}
         {Los impares en negro}
         if Odd(Index) then Canvas.Font.Color:=clRed
                       else Canvas.Font.Color:=clBlack;
         Canvas.FillRect(Rect);
         Canvas.TextOut(Rect.Left,Rect.Top,Items[Index]);
       end;
     end;
    




    The example draws the odd items in red color, and the even items in black color, but you can put your own conditon...

    Ah!, this tip also is valid for a ComboBox...


    Jose Vidal Caballero, comments to me that the tip does not work when we have a ListBox with several columns... and he is all the right!
    Here you have a second version of the tip that works with several columns:

    Instead of use TextOut, this use DrawTextEx

     procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
       Rect: TRect; State: TOwnerDrawState);
     var
       PosTab     : integer;
       dtp        : TDrawTextParams;
     begin
       with (Control as TListBox) do
         begin
           {The Odd Items in Red, the others in black}
           {Los Items pares de color rojo}
           {Los impares en negro}
           if Odd(Index) then Canvas.Font.Color:=clRed
                         else Canvas.Font.Color:=clBlack;
    
           Canvas.FillRect(Rect);
    
           with dtp do begin
             cbSize:=SizeOf(TDrawTextParams);
             iTabLength:=TabWidth;
             iLeftMargin:=0;
             iRightMargin:=0;
           end;
           DrawTextEx( Canvas.Handle,
                       PChar(Items[Index]),
                       Length(Items[Index]),
                       Rect,DT_LEFT or DT_EXPANDTABS or DT_TABSTOP,@dtp);
         end;
     end;