Frage

I have ListView (vsReport) and StringGrid and what I want is if I click on some element in ListView, particular cells in StringGrid have to change colors. How do I do it?

Path is filled with 1 (move up) and 0(move right), it starts in left bottom and ends in right top corner, and I have to color these cells.


Thanks for the answers, I handled with my problem, but there's another little issue, how can I leave text in cells visible? FillRect fills the entire cell.

procedure TForm1.ListView1SelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
var aRect: TRect;
     a,x,y:integer;
     path:string;
begin
  path:=ListView1.Items[Item.Index].Caption;

  x:=0;
  y:=StringGrid1.RowCount;
for a := 0 to length(path) do
  begin
   if path[a]='1' then y:=y-1 else x:=x+1;
   aRect := StringGrid1.CellRect(x-1,y-1);
   StringGrid1.Canvas.Brush.Color := clBlue;
   StringGrid1.Canvas.FillRect(aRect);
   end;
end; 
War es hilfreich?

Lösung

  1. Realize that a cell's color change should be permanent, so that when the StringGrid is painted again, e.g. when the StringGrid was obfuscated by a dialog, also the special colors should be painted again.
  2. Thus you need to store the desired colors somewhere. Say you want to use an array for that, then make a choice between:
    • Storing the special colors along with the grid coordinates in a one-dimensional array. This is good for memory usage, but you would need to search this entire array for the specific coordinate which the StringGrid's OnDrawCell handler (see step 3) provides,
    • Storing only the special colors in a two-dimensional array. This is good for speed when drawing, but you need to synchronize the array's column and row bounds to that of the StringGrid,
    • Or, when you do not need the Objects property of the StringGrid for any purpose, you could employ this property for color storage by typecasting the color to and from a TObject. Shout if you need help with that.
  3. Paint the colored cells in a StringGrid's OnDrawCell event handler (search here on Stack Overflow for [Delphi] StringGrid OnDrawCell when in need of assistance with that).
  4. The ListView's OnSelectItem event exposes the Item which is clicked or otherwise selected.
  5. Retrieve necessery information from that item or its sub-items to determine which cell is to be changed in what color.
  6. Add that information to the chosen storage solution of step 2.
  7. Realize that when all painting now is done "automatically", just a call to StringGrid.Repaint should be enough.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top