Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView color items at runtime

I know that i can set custom colors to items when i add them to the list using OnDraw Events but i want to change colors of the items at a certain point after they are already in the list.

Is there a way to do this ?

like image 865
opc0de Avatar asked Feb 24 '12 12:02

opc0de


1 Answers

To redraw only certain items use the UpdateItems method. It has two input parameters where you can specify the range of the items to be redrawn. If you are going to redraw only one item, then just specify that one item index as a range.

In this example I'm storing the color of the item into the TListItem.Data property and fading this color in the timer's event. After changing the value I call the UpdateItems function which force the draw item event to fire. And yes, without DoubleBuffered set, it flickers (even when you set the timer's interval e.g. to 500ms).

procedure TForm1.FormCreate(Sender: TObject);
begin
  ListView1.AddItem('Item 1', TObject(clWhite));
  ListView1.AddItem('Item 2', TObject(clWhite));
  ListView1.AddItem('Item 3', TObject(clWhite));
  Timer1.Enabled := True;
end;

procedure TForm1.ListView1CustomDrawItem(Sender: TCustomListView;
  Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
  ListView1.Canvas.Brush.Color := TColor(Item.Data);
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var
  C: Byte;
  I: TColor;

  procedure ChangeItemColor;
  begin
    I := TColor(ListView1.Items[0].Data);
    C := GetRValue(I);
    if C < 150 then C := 255 else Dec(C);
    I := RGB(C, C, C);
    ListView1.Items[0].Data := TObject(I);
  end;

begin
  // color change
  ChangeItemColor;
  // repaint of the item with index 1
  ListView1.UpdateItems(1, 1);
end;
like image 112
TLama Avatar answered Nov 16 '22 13:11

TLama