Uploading .csv or .txt file to populate QTableView

2020-06-27 12:50发布

问题:

Recently I was working on a gui application & I wanted to save the data of QTableView in a .csv or .txt file. I Used the guidance received during this question which made me think if the reverse is also possible; i.e. if the QTableView can be populated from a .csv or .txt file. Once again I would prefer staying with a model based design such as QTableView instead of item based QTableWidget.

Any code-snippet or tutorial-documentation would be really helpful.

回答1:

Consider a test.csv file (it could be generated by any text editor):

And the textstream behind is (if generated by programming):

1,2,3,\n4,5,6,\n7,8,9,\n10,11,12,\n13,14,15,

If opened in Microsoft Office Excel, it might looked like:


To read this .csv file to the model of your 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 could manipulate the code to meet you table format)


[Result]



标签: c++ qt qt4