Question

I have so many things in my QGraphicsScene. The situation is I am creating a chessboard, and is using Graphics scene. So the QGraphicsScene is having so many QGraphicsPixmapItems. Now In this how can I get the King.

Update: In this QGraphicsScene, I am adding QGraphicsPixmapItems which are nothing but coins(board,king,queen,soldiers,etc). Now if I want to move a particular coin say King, then How can I get it. There are some methods like using iterators. But is there any way to find a particular QGraphicsPixmapItem by it's name.

Was it helpful?

Solution

When you say you need to get the King, how do you make the difference in your program between the white King and the black one ?

If you need to get a Pawn, how do you know which one ? Anyone ? The first one you can find in your items ?

I haven't thought a lot about it, but maybe what you can do is using a QMap. The key would be a enumeration of the different pieces and the value would be a pointer to the relevant QGraphicsItem. Something like this :

enum Piece_e {
    KING,
    QUEEN,
    ROOK1,
    ROOK2,
    ...
    PAWN1,
    PAWN2,
    ...
};

QMap<Piece_e, QGraphicsPixmapItem*> WhitePiecesItems;
QMap<Piece_e, QGraphicsPixmapItem*> BlackPiecesItems;

When you are creating your scene and instanciating your pieces, you'll fill the map :

...
WhitePiecesItem[KING] = new QGraphicsPixmapItem(QPixmap("whiteking_pic"));
WhitePiecesItem[PAWN1] = new QGraphicsPixmapItem(QPixmap("whitepawn_pic"));
...

BlackPiecesItem[QUEEN] = new QGraphicsPixmapItem(QPixmap("whitequeen_pic"));
BlackPiecesItem[PAWN1] = new QGraphicsPixmapItem(QPixmap("whitepawn_pic"));
...

When you need to find the object corresponding to the white king, you could do something like this :

QGraphicsPixmapItem* pItem = WhitePiecesItem[KING];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top