I have a QStandardItemModel and I need to iterate through it so I can write a custom format line to text file. Can't figure it out.
Solved
General and Desktop
-
I have a QStandardItemModel that's been sorted into a QSortFilterProxyModel. I need to iterate through all of it's records and pull the data and create a text line that I can append to a file.
Here's my model:
QStandardItemModel *model = new QStandardItemModel(0, 3, parent); model->setHeaderData(0, Qt::Horizontal, QObject::tr("Name")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("Data")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Source"));
Here's some code I found in another answer elsewhere but it doesn't work:
// DO FILE WRITES int n = proxyModel->sourceModel()->rowCount(); int m = proxyModel->sourceModel()->columnCount(); for (int i=0; i<n; ++i) { for (int j=0; j<m; j++) { QMap thisItem = proxyModel->sourceModel()->itemData(proxyModel->sourceModel()->index(i,j)); QString thisLine; thisLine = thisLine + thisItem + ","; textOut << thisLine; } } textOut << endl;
Anyone have any ideas?
-
I figured it out:
// DO FILE WRITES int n = proxyModel->sourceModel()->rowCount(); int m = proxyModel->sourceModel()->columnCount(); for (int i=0; i<n; ++i) { QString thisName = proxyModel->sourceModel()->data(proxyModel->sourceModel()->index(i, 0)).toString(); QString thisValue = proxyModel->sourceModel()->data(proxyModel->sourceModel()->index(i, 1)).toString(); QString thisSource = proxyModel->sourceModel()->data(proxyModel->sourceModel()->index(i, 2)).toString(); QString thisLine; thisLine = thisLine + thisName + "," + thisValue + "," + thisSource + ","; textOut << thisLine; } textOut << endl;
-
@RobbieP
This is fine, but you should not have to do everything so long-windedly throughproxyModel->sourceModel()
calls. Did you try e.g.int n = proxyModel->rowCount(); ... QString thisName = proxyModel->index(i, 0).data().toString();
Also note this outputs in the "sorted into a
QSortFilterProxyModel
" order, your original outputs in the underlying, unsortedQStandardItemModel
order. Depends which you want.