In my current project, I have an array of QCheckBoxes that I create at run-time given the dimensions from the user. Every time the user clicks the ‘Generate’ button, the dimensions that they inputted are gathered, and an array of QCheckBoxes is created. It is done in the following code:
void MainWindow::on_generateBoxes_clicked()
{
int x_dim = ui->xDim->value();
int y_dim = ui->yDim->value();
int z_dim = ui->zDim->value();
for(int i = 0; i < x_dim; ++i){
for(int j = 0; j < y_dim; ++j){
checkBoxVector.append(new QCheckBox( ui->dim1 ));
checkBoxVector.last()->setGeometry(i * 20, j * 20, 20, 20);
}
}
}
checkBoxVector is a global array of pointers declared in another source file:
QVector<QCheckBox*> checkBoxVector;
My question is, how would I go through checkBoxVector to remove every QCheckBox? Since the previous dimensions of the array are local variables that are lost once the function returns, when it is re-called how would I know how many elements to remove?
If the user was to press the ‘Generate’ button twice there would be overlapping QCheckBoxes, so I need to wipe them all every time the function is called. (Also, nobody wants a memory leak!)
First delete all the elements (QCheckBoxes) in the vector and then clear the vector:
Because you are adding checkbox pointers to the vector, just clearing the vector doesn’t delete the checkboxes.