test11 test11 - 2 months ago 23
C++ Question

Model of the QTableView dosent view values as desired

I have a QTableview with model. I populate dummy data in the model using this code

horizontalHeader.append("Name");
horizontalHeader.append("Type");
horizontalHeader.append("Unit price");
horizontalHeader.append("qty");
item00 = new QStandardItem(QString("0"));
item01 = new QStandardItem(QString("0"));
item02 = new QStandardItem(QString("0"));
item03 = new QStandardItem(QString("0"));
QList<QStandardItem*> list;

list.push_back(item00);
list.push_back(item01);
list.push_back(item02);
list.push_back(item03);

for (int i=0; i<100; i++){
list.at(0)->setText(QString::number(i));
list.at(1)->setText(QString::number(i));
list.at(2)->setText(QString::number(i));
list.at(3)->setText(QString::number(i));
model.insertRow(i,list);
}


the result should be a table of 100 rows and four columns and the content of the rows is a number but instead I am getting a the first row populated with data and the other rows are just empty as per the following screenshot
enter image description here

Answer

You are inserting the same QStandardItems a 100 times, this should result in a warning:

QStandardItem::insertRows: Ignoring duplicate insertion of item 0xxxxxxxxx

For every insert operation, starting from the second.So, in your code, The insert operation will be ignored, and you set the QStandardItem (that was already inserted in the first operation) to the new value of i (that explains why you get one row 99s in it).

Instead, you should use new QStandardItems for each row insert, like this:

for (int i=0; i<100; i++){
    QList<QStandardItem*> list;
    list.append(new QStandardItem(QString::number(i)));
    list.append(new QStandardItem(QString::number(i)));
    list.append(new QStandardItem(QString::number(i)));
    list.append(new QStandardItem(QString::number(i)));
    model.insertRow(i,list);
}