To display some data in QTableView
, I use a function to compute the QStandardItemModel
and sent it back to the calling function.
Function Call:
QStandardItemModel MyModel = computeMyModel();
ui->tV->setModel(&MyModel);
Called Function
QStandardItemModel computeMyModel()
{
QStandardItemModel newModel;
//........... Steps to compute newModel
return newModel;
}
I get the following error when I try to run the code.
error C2248: 'QStandardItemModel::QStandardItemModel' : cannot access private member declared in class 'QStandardItemModel'
How to solve this problem?(How to successfully pass the myModel from one function to another without call by refernce?)
Constraints:
computeMyModel()
function only.computeMyModel()
through call by reference. Try this:
QStandardItemModel* computeMyModel()
{
int counter = 0;
QStandardItemModel *model = new QStandardItemModel;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
{
counter++;
QStandardItem *item = new QStandardItem(QString::number(counter));
model->setItem(i,j,item);
}
return model;
}
Using:
QStandardItemModel *model = computeMyModel();
ui->tableView->setModel(model);
No. It will be normal, because you allocate memory and return a pointer, your pointer has this memory address and it will have it until something deletes it. To prove this, see this code snippet. As you can see, you allocate memory in the function, return a pointer, set data using this pointer and call setModel
. It compiles and works.
Function:
QStandardItemModel* computeMyModel()
{
QStandardItemModel *model = new QStandardItemModel;
return model;
}
Using
int counter = 0;
QStandardItemModel *model = computeMyModel();
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
{
counter++;
QStandardItem *item = new QStandardItem(QString::number(counter));
model->setItem(i,j,item);
}
ui->tableView->setModel(model);