我有QT向量的问题。我有一个指针向量的向量:
QVector <QVector <QGraphicsRectItem*> > Board;
创建QGraphicsItems的函数返回指针,所以我需要这个结构。 问题是我无法访问项目。我写的时候
Board[Row][Column]
它只能使列正确。
我也尝试制作像“
”这样的“适当”指针2d向量QVector <QVector <QGraphicsRectItem*>*> Board;
但是当我这样做的时候程序会崩溃。
我该如何处理这个问题?
完整代码以防万一:
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);
}
答案 0 :(得分:3)
您忘了清除tempRow
:
Board.push_back(tempRow);
tempRow.clear(); // add this
如果不清除,您会继续将行添加到行尾,这不是您想要的。