Loading .csv or .txt file to populate QTableView
I was working on a GUI application recently and I wanted to save the QTableView data in a .csv or .txt file. I used the guidance I received during this question , which made me think if the opposite is possible. that is, if the QTableView can be populated from a .csv or .txt file. Once again, I would prefer to stay with a model design like QTableView rather than item based QTableWidget.
Any code snippet or tutorial documentation would be really helpful.
source to share
Consider a file test.csv
(it can be generated by any text editor):
And the text stream behind (if generated by programming):
1,2,3,\n4,5,6,\n7,8,9,\n10,11,12,\n13,14,15,
If it is open in Microsoft Office Excel, it might look like this:
To read this file .csv
into your model QTableView
:
QStandardItemModel *model = new QStandardItemModel;
QFile file("test.csv");
if (file.open(QIODevice::ReadOnly)) {
int lineindex = 0; // file line counter
QTextStream in(&file); // read to text stream
while (!in.atEnd()) {
// read one line from textstream(separated by "\n")
QString fileLine = in.readLine();
// parse the read line into separate pieces(tokens) with "," as the delimiter
QStringList lineToken = fileLine.split(",", QString::SkipEmptyParts);
// load parsed data to model accordingly
for (int j = 0; j < lineToken.size(); j++) {
QString value = lineToken.at(j);
QStandardItem *item = new QStandardItem(value);
model->setItem(lineindex, j, item);
}
lineindex++;
}
file.close();
}
(You can manipulate the code to fit the tabular format)
[Result]
source to share