Search code examples
firemonkeydelphi-xe8

firemonkey add item to HorzScrollBox on the fly


i have a Horizontal Scroll Box item on my form.after run the program i will get a json string that include the list of items that must be in Horizontal Scroll Box .and i must add them dynamically.

for example i have this : enter image description here after run the program in the ? area i must a a new image.

i found the function : HorzScrollBox1.AddObject(); but a argument is required for this

i have two question:

1)how can i add the new object to this?

2)can i clone an existing image and add it at the end of the list?


Solution

  • Add object: there are two ways - set Parent property of children or execute AddObject method of parent. Parent property setter has some checks, and call AddObject. Depending on control class, child object can be added to Controls collection of the control or to its Content private field. Not all classes provide access to this field (in some cases you can use workaround, like in this question). HorzScrollBox has this field in public section.

    So, if you want to clone existing image, you must:

    1. Get existing image from Content of HorzScrollBox

    2. Create new image and set it properties

    3. Put new image to HorzScrollBox.

    For example:

    procedure TForm2.btnAddImgClick(Sender: TObject);
      function FindLastImg: TImage;
      var
        i: Integer;
        tmpImage: TImage;
      begin
        Result:=nil;
        // search scroll box content for "most right" image
        for i := 0 to HorzScrollBox1.Content.ControlsCount-1 do
          if HorzScrollBox1.Content.Controls[i] is TImage then
            begin
              tmpImage:=TImage(HorzScrollBox1.Content.Controls[i]);
              if not Assigned(Result) or (Result.BoundsRect.Right < tmpImage.BoundsRect.Right) then
                Result:=tmpImage;
            end;
      end;
    
      function CloneImage(SourceImage: TImage): TImage;
      var
        NewRect: TRectF;
      begin
        Result:=TImage.Create(SourceImage.Owner);
        Result.Parent:=SourceImage.Parent;
    
        // Copy needed properties. Assign not work for TImage...
        Result.Align:=SourceImage.Align;
        Result.Opacity:=SourceImage.Opacity;
        Result.MultiResBitmap.Assign(SourceImage.MultiResBitmap);
    
        // move new image
        NewRect:= SourceImage.BoundsRect;
        NewRect.Offset(NewRect.Width, 0); // move rect to right.
        Result.BoundsRect:=NewRect;
      end;
    begin
      CloneImage(FindLastImg);
    end;