Qt/C++ - Lesson 054. Reading data from a CSV file, and their representation via QStandardItemModel

CSV, QStandardItemModel, Qt, QTableView

CSV data format ( Comma-Separated Values ) format is the simplest representation of tabular data. This format is supported by Excel and many other office suites. For example, I often encounter this format when uploading statistics do the site of the panel webmasters Google Search Console.

In this format, the table represents the data sequence, separated by commas, and represent the column and row are separated by a newline. In the case of the Russian-language Microsoft Excel data separated by semicolons and will be as follows:

BMW;X5;3000000
Lada;Kalina;250000

Parsing CSV

So the whole problem is reduced to a line reading data from a file and uploads the data model of data presentation, which will be placed in QTableView .

Let us take as a basis the above example, the contents of a CSV file that was created in Microsoft Excel:

And display it in QTableView via QStandardItemModel:

mainwindow.h

The appearance of the application was created in the Graphics Designer, so to QTableView appeal goes through the ui object.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QStandardItemModel>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
 
private:
    Ui::MainWindow *ui;
    QStandardItemModel *csvModel;  
};
 
#endif // MAINWINDOW_H

mainwindow.cpp

CSV file in this example is placed in the project's resource file, if you want to specify a file, respectively, need to rewrite the path to this file. The result will be in accordance with what was shown in the screenshot above.

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // Create a data model for the mapping table from a CSV file
    csvModel = new QStandardItemModel(this);
    csvModel->setColumnCount(3);
    csvModel->setHorizontalHeaderLabels(QStringList() << "Марка" << "Модель" << "Цена");
    ui->tableView->setModel(csvModel); 
 
    // Open the file from the resources. Instead of the file
    // Need to specify the path to your desired file
    QFile file(":/exampleTable.csv");
    if ( !file.open(QFile::ReadOnly | QFile::Text) ) {
        qDebug() << "File not exists";
    } else {
        // Create a thread to retrieve data from a file
        QTextStream in(&file);
        //Reads the data up to the end of file
        while (!in.atEnd())
        {
            QString line = in.readLine();
            // Adding to the model in line with the elements
            QList<QStandardItem *> standardItemsList;
            // consider that the line separated by semicolons into columns
            for (QString item : line.split(";")) {
                standardItemsList.append(new QStandardItem(item));
            }
            csvModel->insertRow(csvModel->rowCount(), standardItemsList);
        }
        file.close();
    }
}
 
MainWindow::~MainWindow()
{
    delete ui;
    delete csvModel;
}

Download the archive with an example csv and QStandardItemModel

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

https://evileg.com/en/post/158/

Also, I would like to get a list of specific column with its items to use it for another function. How can I retrieve it?

Comments

Only authorized users can post comments.
Please, Log in or Sign up
G
July 23, 2019, 3:47 a.m.
G0tzef

C++ - Test 001. The first program and data types

  • Result:66points,
  • Rating points-1
AS
July 22, 2019, 4:32 p.m.
Aleksandr Spiridonov

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
AS
July 22, 2019, 4:21 p.m.
Aleksandr Spiridonov

Qt - Test 001. Signals and slots

  • Result:73points,
  • Rating points1
Last comments
July 23, 2019, 12:14 p.m.
IscanderChe

Вот ссылка: https://github.com/iscander-che/TestReportViewer .
July 23, 2019, 5:42 a.m.
Evgenij Legotskoj

Хорошо, хотя конечно это С, а не С++ )))) Но если вдруг будут проблемы, то решение через класс со статическими переменными вы видели ))
July 23, 2019, 5:33 a.m.
IscanderChe

"Не потребует каждый раз объявлять extern в других файлах". И так не требует. У меня в тестовом классе эти переменные используются без дополнительного объявления. Так же объявил их в cpp-файле о…
July 23, 2019, 5:28 a.m.
IscanderChe

В репозиторий могу сегодня вечером выложить. "Или ее надо компилить самому под дистриб?" Тут я не совсем понимаю, что вы имеете ввиду. Я выложу в репозиторий исходный код утилиты, и всё.
July 23, 2019, 4:32 a.m.
Evgenij Legotskoj

Есть комментарий по вашему коду. Лучше бы вместо глобальных переменных в стиле Си, то есть с использоавнием extern, написали бы статические переменные в рамках класса. IMHO - это будет выглядеть…
Now discuss on the forum
July 23, 2019, 10:36 a.m.
Evgenij Legotskoj

Добрый день. Возможно, что проблема в поддержке OpenGL на виртуальной машине.
July 23, 2019, 8:20 a.m.
Mihailll

Так работает QFile f1(dbAdress); f1.setPermissions(QFileDevice::WriteOther);
July 23, 2019, 7:11 a.m.
Pavel K.

Советую использовать нечто такое или такое
July 22, 2019, 10:50 a.m.
Pavel K.

Благодарю.Буду пробовать.
Looking for a Job?
5,000.00 руб. - 15,000.00 руб.
Дизайнер
Moskovskiy, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB