c++qtqtableviewqabstractitemmodelqstandarditemmodel

How to pass QStandardItemModel from a function?


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:

  1. I have to compute the model in computeMyModel() function only.
  2. I don't like to pass a model from the calling function to the computeMyModel() through call by reference.

Solution

  • 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);
    
    Update

    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);