How can I programmatically fill a GridContainer?

Godot Version

4.2.1

Question

I try to programmatically add a GridContainer to a Node2D:

public override void _EnterTree(){
  var grid = new GridContainer()
  {
  	Position = new Vector2(GetViewportRect().Size.X/2, GetViewportRect().Size.Y/2),
  	Columns = 2,
  	
  };
  
  for( var i = 0; i < 20; ++i)
  {			
  	var container = new Control(){
  		Size = new Vector2(100, 100)
  	};	
  
  	container.AddChild(new ColorRect(){
  		Size = new Vector2(100, 100),
  		Color = new Color(i/20f, i/20f, 1)
  	});
  
  	grid.AddChild(container);
  }
}

AddChild(grid);

The result looks like GridControl thinks the first elements are only 1x1 in size:

image

Containers use their children size flags and minimum size to setup the position and size.

Setting a Control.size value is not setting its minimum size. Containers will override this value when sorting their children.

To set a minimum size you need to change the Control.custom_minimum_size property to your desired minimum size.

1 Like

Perfect and easy solution, I added a CustomMinimumSize = new Vector2(100, 100) below the Size assignment in the contorl node.