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
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
AP
June 2, 2020, 10:11 p.m.
Aleksej Pikenin

C++ - Test 005. Structures and Classes

  • Result:75points,
  • Rating points2
June 2, 2020, 2:04 p.m.
Daniil Chizhevskij

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

  • Result:86points,
  • Rating points6
a
June 1, 2020, 11:15 a.m.
alekseyttrv

C++ - Test 005. Structures and Classes

  • Result:83points,
  • Rating points4
Last comments
May 31, 2020, 9:15 a.m.
IscanderChe

Как установить OpenCV на Qt под Windows

Добавлю от себя: на Windows 10 x64 с MinGW 7.3.0 в CMake надо установить флаг OPENCV_ENABLE_ALLOCATOR_STATS=OFF, тогда всё скомпилится нормально.
May 29, 2020, 2 p.m.
Evgenij Legotskoj

Django - Tutorial 023. Like Dislike system using GenericForeignKey

Думал так, но похоже что нет. {{ post.votes.likes.user.username }} Это же QuerySet будет, а не отдельный единственный объект {% for vote in post.votes %} {{ vote.user.username …
May 29, 2020, 12:43 p.m.
Vladislav Melenchuk

Django - Tutorial 023. Like Dislike system using GenericForeignKey

А как получить имя пользователя, который поставил лайк? Думал так, но похоже что нет. {{ post.votes.likes.user.username }}
May 29, 2020, 7:30 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

У меня работает. Исправлял в проекте, который приложен к статье. А что происходит в вашем коде, с учётом места вызова этого кода, я знать не могу ;) Дебажьте и добавляйте условия, кото…
Now discuss on the forum
MA
June 2, 2020, 10:40 a.m.
Mihail A

Qt- C++ QTableView подсветить строку

Да, спасибо.
June 2, 2020, 3:46 a.m.
Evgenij Legotskoj

Медиа файлы Google Firebase

Картинки можете попробовать сжимать через QPixmap, там есть возможность установки scaleFactor, через него можете устанавливать нужные параметры. А что касается конвертации видео, то лучше п…
June 2, 2020, 3:01 a.m.
Evgenij Legotskoj

Перехват обращения к локальным файлам QWebEngineView

В вашем случае вполне адекватное решение. Так сказать меньше зло. В противном случае пришлось бы очень много переписывать и перепиливать.
a
June 1, 2020, 11:26 a.m.
alekseyttrv

SSL на Android

у меня стоит версия Qt 5.14.2. В настройках android поставил openssl из коробки, и этот прроект автоматически стянулся. Достаточно было только добавить в .pro-файл строку после этого и все …
June 1, 2020, 3:21 a.m.
Evgenij Legotskoj

QModelIndex становится не действительным, но валидный

Не гоните лошадей. quintptr aid вам не нужно сохранять. Попробуйте ограничиться только колонкой и строкой. А также используете метод index() вашей модели, чтобы по строке и колонке возвраща…
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB