Qtableview open csv file
-
Hi,
I am using qtableview and using action save , saving in a csv file, but when i'm opening the same file then its also adding header in the table, that i don't want,also when I open csv file then the color is not coming ( adding color using a diff function, for speific columns using Qbrush), for rows which are filling through csv
void table_inpiut::action_Open() { QString filters("CSV files (*.csv);"); QString fileName = QFileDialog::getOpenFileName(this, "Open file", QDir::homePath(), filters); QFile file(fileName); QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui.tableView->model()); if (file.open(QIODevice::ReadOnly)){ // QMessageBox::information(0, "Error!", "Error opening file!", 0); int lineindex = 0; // file line counter QTextStream in_file(&file); // read to text stream while (!in_file.atEnd()) { // read one line from textstream(separated by "\n") QString fileLine = in_file.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(); } }
what need to change in this code?
-
Hi,
The header is usually the first line of the file so just ignore it.
As for the colors, are you storing them in the CSV file ?
-
@SGaist // read one line from textstream(separated by "\n")
QString fileLine = in_file.readLine();
in this i should ignore first line, like -1 something or any func. is there ?No color I'm not storing in csv / but it can be case user import somefile which is not saved in this project.
-
Either do one readLine before your while loop or use a Boolean to skip processing the first line you read in your while loop.
As for your color issue, how do you apply it ?
-
@SGaist
ok i'll try this readline
color columns->QAbstractItemModel* abstrctitem_table1 = ui.tableView->model(); for (int irowTable1 = 0; irowTable1 < abstrctitem_table1->rowCount(); ++irowTable1) { for (int columnTable1 : {0, 1, 2, 3, 4, 5, 8}) abstrctitem_table1->setData(abstrctitem_table1->index(irowTable1, columnTable1), QBrush(QColor(240, 248, 255)), Qt::BackgroundRole); } QObject::connect(abstrctitem_table1, &QAbstractItemModel::rowsInserted, abstrctitem_table1, [abstrctitem_table1](const QModelIndex& parent, int first, int last) { for (int irowTable1 = first; irowTable1 <= last;++irowTable1) { for (int columnTable1 : {0, 1, 2, 3, 4, 5, 8}) abstrctitem_table1->setData(abstrctitem_table1->index(irowTable1, columnTable1, parent), QBrush(QColor(240, 248, 255)), Qt::BackgroundRole); } });