I am using a QAbstractTableModel
. The model holds data in it. It is created and deleted upon user clicks.
This is the connected slot after user click to create a model:
void clicked(){
model = new QAbstractTableModel(data);
model->setManyThings();
}
This is the connected slot after user click to clear the model:
void clear(){
if (model != nullptr)
delete model;
}
However, this cannot check whether model
is exist. If I click clear twice the program crash directly. If the model was not created be I click clear, the program crashed directly.
So how to check whether model exist
You are deleting the model
object on the first call, obviously in the second call it crashes because you were trying to call an already deleted object.
In fact, you are actually chekcing if model
exists, if model != nullptr
means that this pointer is pointing to an actual object.
If you want to reset the 'model' object just create a new one after deleting the other:
void clear(){
if (model != nullptr)
{
delete model;
model = new QAbstractTableModel(data);
}
}
If you want to just delete it and continue with the proper checking just set the pointer to nullptr
:
void clear(){
if (model != nullptr)
{
delete model;
model = nullptr;
}
}