Uploading .csv or .txt file to populate QTableView

*爱你&永不变心* 提交于 2019-12-09 13:38:21

问题


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]



来源:https://stackoverflow.com/questions/27354200/uploading-csv-or-txt-file-to-populate-qtableview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!