Search code examples
delphivcl

FlowPanel how to Wrap every given number of components?


is there any way, not that complicated to wrap the components of a FlowPanel for instance every 3 components?

as it works with the property autowrap but by a given amount of controls.

thanks in advance.


Solution

  • You left the actual image sizes open, so here its the general idea with some example sizes that you will have to adopt to your liking. I made some initial tests with buttons (normal width = 75), so I sized the TFlowPanel to 235 px wide.

    The idea is to have a TFlowPanel with a fixed width (Constraints.MaxWidth = 235; Constraints.MinWidth = 235;) but AutoSize=True so it can grow downward. If you add e.g. 75px wide components, 3 of them fit perfectly on one row. If wider, only 2 or even only 1 fit on a row. So far as you wish. But if the width is only 56px (mean value) or less the number of compnents will be four or more.

    I suggest a solution to place such a smaller component on a panel of its own, with a width of 75px, and that panel on the TFlowPanel. Thus no more than three components will fit on one row.

    This is the code with which a number of buttons were placed on a TFlowPanel.

    procedure TForm3.Button1Click(Sender: TObject);
    var
      btn: TButton;
      pan: TPanel;
    begin
      inc(count);
      btn := TButton.Create(self);
      btn.Width := random(60)+35;
      if btn.Width < 75 then
      begin
        pan := TPanel.Create(self);
        pan.Width := 75;
        pan.Height := 30;
        pan.BevelOuter := bvNone;
        btn.Parent := pan;
        pan.Parent := FlowPanel1;
      end
      else
      begin
        btn.Parent := FlowPanel1;
      end;
      btn.Caption := IntToStr(count);
    end;
    

    And the end result

    enter image description here


    Alternative solution

    Another solution (since you mentioned TImages) is to always create the TImages with a width of at least 75px. The picture (if smaller than that) can be centered in the TImage, if you like. This is based on the fact that the image doesn't affect the size of the TImage control (unless you want it to).

    Also, if you don't really absolutely need to show the images in their full actual size, you can set the Proportional property true. From the docs:

    When Proportional is true, images that are too large to fit in the image control are scaled down (while maintaining the same aspect ratio) until they fit in the image control.