Reputation: 191
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. Upvotes: 1
Views: 1076
Reputation: 18504
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);
Upvotes: 4
Reputation: 1
Another approach to achieve this is by passing a model created before hand and manipulating it through a reference.
It's not possible to return a QStandardItemModel
because it's inaccessible, and sending back a pointer doesn't work.
Function:
void computeMyModel(QStandardItemModel& model)
{
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);
}
}
Using:
QStandardItemModel* model = new QStandardItemModel(0, 0, this);
computeMyModel(*model);
ui->tableView->setModel(model);
Upvotes: 0