Ivan
Ivan

Reputation: 16908

Access vector of vectors of pointers in QT

I have a problem with QT vectors. I have a vector of vectors of pointers:

QVector <QVector <QGraphicsRectItem*> > Board;

Functions creating QGraphicsItems return pointers, so i need this structure to be like that. The problem is i can't access items. When i write

Board[Row][Column]

it only gets the column right.

I also tried making a "proper" 2d vector of pointers like

QVector <QVector <QGraphicsRectItem*>*> Board;

But when i do it like this the program crashes.

How can i deal with this problem?

Full code just in case:

chessboard.h:

#ifndef CHESSBOARD_H
#define CHESSBOARD_H
#include <QWidget>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsItem>
namespace Ui {
class ChessBoard;
}
class ChessBoard : public QWidget
{
    Q_OBJECT
public:
    explicit ChessBoard(QWidget *parent = 0);
    ~ChessBoard();
    QVector <QVector <QGraphicsRectItem*> > Board;
    void fillChessBoard();
    void Highlight (int row, int column);
private:
    Ui::ChessBoard *ui;
    QGraphicsScene *scene;
};
#endif // CHESSBOARD_H

chessboard.cpp:

#include "chessboard.h"
#include "ui_chessboard.h"
#define BOARD_SIZE 8

ChessBoard::ChessBoard(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChessBoard)
{
    ui->setupUi(this);
    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);
    fillChessBoard();
    Highlight(3,5);



}
ChessBoard::~ChessBoard()
{
    delete ui;
}
void ChessBoard::fillChessBoard()
{
    QBrush blackBrush (Qt::black);
    QBrush whiteBrush (Qt::white);
    QPen outlinePen (Qt::black);
    outlinePen.setWidth(1);
    QGraphicsRectItem* tempRect;
    QVector <QGraphicsRectItem*> tempRow;
    bool colorSwitch=0;
    for (int i=0;i<BOARD_SIZE;i++)//j-x;i-y
    {
        for (int j=0; j<BOARD_SIZE;j++)
        {
            if(colorSwitch==0)
            {
                tempRect=scene->addRect(j*50,i*50,50,50,outlinePen,whiteBrush);
                tempRow.push_back(tempRect);
                colorSwitch=!colorSwitch;
            }
            else
            {
                tempRect=scene->addRect(j*50,i*50,50,50,outlinePen,blackBrush);
                tempRow.push_back(tempRect);
                colorSwitch=!colorSwitch;
            }
        }
        colorSwitch=!colorSwitch;
        Board.push_back(tempRow);
    }
}

void ChessBoard::Highlight(int row,int column)
{
    QBrush redBrush (Qt::red);
    Board[row][column]->setBrush(redBrush);
}

Upvotes: 0

Views: 1060

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

You forgot to clear tempRow:

Board.push_back(tempRow);
tempRow.clear(); // add this

Without clearing, you continue to add items to the end of row which is not what you want.

Upvotes: 3

Related Questions