QWidget* centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
QVBoxLayout* mainLayout = new QVBoxLayout(centralWidget);
topLineLayout = new QHBoxLayout();
minesCounterLabel = new QLabel();
emoticonButton = new QPushButton();
timerLabel = new QLabel("0");
topLineLayout -> addWidget(minesCounterLabel);
topLineLayout -> addWidget(emoticonButton);
topLineLayout -> addWidget(timerLabel);
mainLayout -> addLayout(topLineLayout);
paddingLayout = new QGridLayout();
paddingLayout -> setSpacing(0);
std::vector <Cell> cellsVector;
for(int i = 0; i < paddingHeight; i++)
{
for(int j = 0; j < paddingWidth; j++)
{
Cell* cell = new Cell(&cellsVector, j, i, false);
cellsVector.push_back(*cell);
}
}
for(int i = 0; i < cellsVector.size(); i++)
{
paddingLayout -> addWidget(&cellsVector[i], cellsVector[i].getX(), cellsVector[i].getY());
}
mainLayout -> addLayout(paddingLayout);
这是mainwindow.h文件,这是mainwindow类构造函数的提取。我不明白的是,为什么Paddinglayout不显示任何添加到其上的小部件,在这种情况下为"单元格"。有什么想法吗?
编辑:
类"单元"的定义和其构造函数的代码:
class Cell : public QPushButton
{
Q_OBJECT
public:
Cell(std::vector <Cell> *, int, int, bool, QWidget* parent = 0);
Cell(const Cell&);
bool hasMine();
int getX();
int getY();
std::vector <Cell> * getCellsVector();
void setHasMine(bool);
~Cell();
Cell operator=(const Cell& object)
{
this -> cellsVector = object.cellsVector;
this -> mine = object.mine;
this -> x = object.x;
this -> y = object.y;
setFixedSize(20, 20);
connect(this, &QPushButton::clicked, this, &Cell::cellClicked);
}
private:
std::vector <Cell> * cellsVector;
int x;
int y;
bool mine;
// Determine how many mines are around this cell.
int countMines();
void cellClicked();
};
Cell::Cell(std::vector <Cell> * cellsVector, int x, int y, bool mine = false, QWidget* parent) : QPushButton(parent)
{
this -> cellsVector = cellsVector;
this -> mine = mine;
this -> x = x;
this -> y = y;
setFixedSize(20, 20);
connect(this, &QPushButton::clicked, this, &Cell::cellClicked);
}
Cell::Cell(const Cell& object)
{
this -> cellsVector = object.cellsVector;
this -> mine = object.mine;
this -> x = object.x;
this -> y = object.y;
setFixedSize(20, 20);
connect(this, &QPushButton::clicked, this, &Cell::cellClicked);
}
如果需要更多代码,请说!
首先,单元格操作员的问题应为
Cell& operator=(const Cell& object)
{
if (&object == this) return *this;
this -> cellsVector = object.cellsVector;
this -> mine = object.mine;
this -> x = object.x;
this -> y = object.y;
setFixedSize(20, 20);
connect(this, &QPushButton::clicked, this, &Cell::cellClicked);
return *this; // you must return value
}
大问题是在std::vector <Cell> cellsVector;
中,创建了此向量,将单元格插入其中,然后在此行中
paddingLayout -> addWidget(&cellsVector[i], cellsVector[i].getX(), cellsVector[i].getY());
您获取单元格的地址,然后将其传递给 qgridlayout ,但是在功能结束时,cellsVector
会发生什么?该矢量被破坏,并且所有细胞也被破坏。 qgridlayout 将指针删除对象。