Beginner
Grid Layout
Arrange Positionable components into a uniform grid automatically. Change position, row count, or spacing and all items reflow immediately.
Introduction
Basic Grid Setup
ml::Grid arranges components into a uniform grid automatically. It recalculates all positions whenever a component is added or any layout parameter changes. Items fill cells in row-major order (left-to-right, top-to-bottom).
Creating a grid
cpp
// 4 columns, 3 rows
ml::Grid grid({4, 3}); // x = columns, y = rows
grid.setPosition({80.f, 140.f});
grid.setSpacing(12.f);
// Add components — they are positioned automatically
for (auto& tile : _tiles)
grid.addItem(tile);
// Register with addItem() for layout; also call addComponent() on the app for events/drawing
Never copy or move a component after adding it to a Grid. The grid stores raw pointers. Moving the object invalidates the pointer.
1Core Concepts
Grid API Reference
| Method | Description |
|---|---|
Grid(sf::Vector2u size) | Construct with size.x columns and size.y rows. |
addItem(Core&) | Add an item to the grid layout and trigger reposition(). |
setRow(int) | Set columns per row. Triggers reposition(). |
setSpacing(float) | Set gap between cells in pixels. Triggers reposition(). |
setPosition(sf::Vector2f) | Set top-left origin. All items shift together. |
getGlobalBounds() | Bounding box covering all cells including spacing. |
Dynamic reconfiguration and practical example
cpp
ml::Grid board({8, 8}); // 8×8 chess board
board.setPosition({160.f, 100.f});
board.setSpacing(2.f);
for (int i = 0; i < 64; i++) {
_tiles[i].setSize({72.f, 72.f});
bool light = (i / 8 + i % 8) % 2 == 0;
_tiles[i].setFillColor(light
? sf::Color(240, 217, 181) // light square
: sf::Color(181, 136, 99)); // dark square
_tiles[i].onClick([i, this]{ handleTileClick(i); });
board.addItem(_tiles[i]);
}
// Dynamically change column count — items reflow automatically
board.setRow(4);
// Move the whole grid — all items shift together
board.setPosition({100.f, 150.f});