Solved Import .CSV data to QTableView
-
Hi! I wanna read data from .csv file into QTableView.
I used this code, but it doesn't work. How to fix that? Please helpQStandardItemModel *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(); } ui->tableView->setModel(model);```// It doesn't work
-
@ro12man3 said:
hi , does it read the data from the file?
You should check if any in list
qDebug << "fields:" << lineToken.size();
-
@mrjj no. It doesn't. I was found that solution here http://stackoverflow.com/questions/27354200/uploading-csv-or-txt-file-to-populate-qtableview .
But I don't know how to integrate this with qtableview -
@ro12man3
Well code looks fine :)
So if u dont get any in list, it means file empty or wrong format.can u post the first 10 lines from file u read in?
also test with
qDebug() << "reading:" << fileLine ;
-
@mrjj well, it still doesn't work.
The data in .csv file is very simple:
2 4 6
1 3 5 -
@ro12man3 Take a look at this line:
QStringList lineToken = fileLine.split(",", QString::SkipEmptyParts);
it is splitting on ',' character not blanks!
Change it to:QStringList lineToken = fileLine.split(' ', QString::SkipEmptyParts);
-
@jsulm I changed on that
QStringList lineToken = fileLine.split(";", QString::SkipEmptyParts);
and now it's working correctly