One or more of these Custom GraphicsItems can be added to the View/Scene - and the problem I'm having is that they will be added in the same place by default, and I can't see an obvious and simple way of arranging them so that they will not collide with each other when the view is redrawn.
Who is doing the adding? If it is being done in response to a button click or whatever, put some state information into the class managing the scene that "knows" about the next available grid location and move the object after it is added to the scene, or even better just add it at the right location. Resorting to some type of graphing algorithm library for something as simple as laying out rectangles in a grid seems like overkill to me.
"Next available grid location" could be as simple as:
// pseudocode
void myClass::addNewItemAtNextLocation()
{
// itemIndex is a member variable, initialized to zero in constructor
// itemsPerRow could be fixed or might depend on view size
// horzGap and vertGap is the empty space between rects so their edges don't coincide
int rowNumber = int( itemIndex / itemsPerRow );
int colNumber = int( itemIndex % itemsPerRow );
QPointF itemPos
= QPointF( colNumber
* (itemWidth
+ horzGap
), rowNumber
* (itemHeight
+ vertGap
) );
CustomItem
* item
= new CustomItem
( QRectF( itemPos, itemSize
) );
scene.addItem( item );
itemIndex++;
}
// pseudocode
void myClass::addNewItemAtNextLocation()
{
// itemIndex is a member variable, initialized to zero in constructor
// itemsPerRow could be fixed or might depend on view size
// horzGap and vertGap is the empty space between rects so their edges don't coincide
int rowNumber = int( itemIndex / itemsPerRow );
int colNumber = int( itemIndex % itemsPerRow );
QPointF itemPos = QPointF( colNumber * (itemWidth + horzGap), rowNumber * (itemHeight + vertGap) );
QSizeF itemSize = QSizeF( itemWidth, itemHeight );
CustomItem * item = new CustomItem( QRectF( itemPos, itemSize ) );
scene.addItem( item );
itemIndex++;
}
To copy to clipboard, switch view to plain text mode
This will add new items across then down. If the items can be dynamically added and removed or moved from cell-to-cell, then you'd need a more sophisticated way to keep track of which cells are empty, or if it is acceptable in your GUI, removing an item could simply shift everything above it down by one index location.
Bookmarks