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 help

    QStandardItemModel *model = new QStandardItemModel;
    QFile file("test.csv");
    if ( {
        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 =;
                QStandardItem *item = new QStandardItem(value);
                model->setItem(lineindex, j, item);
    ui->tableView->setModel(model);```// It doesn't work

  • Qt Champions 2017

    @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 .
    But I don't know how to integrate this with qtableview

  • Qt Champions 2017

    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

  • Moderators

    @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

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.