Evgenii Legotckoi
Aug. 28, 2016, 9:08 p.m.

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

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:

  1. BMW;X5;3000000
  2. 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.

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QStandardItemModel>
  6.  
  7. namespace Ui {
  8. class MainWindow;
  9. }
  10.  
  11. class MainWindow : public QMainWindow
  12. {
  13. Q_OBJECT
  14.  
  15. public:
  16. explicit MainWindow(QWidget *parent = 0);
  17. ~MainWindow();
  18.  
  19. private:
  20. Ui::MainWindow *ui;
  21. QStandardItemModel *csvModel;
  22. };
  23.  
  24. #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.

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. #include <QFile>
  4. #include <QTextStream>
  5. #include <QDebug>
  6.  
  7. MainWindow::MainWindow(QWidget *parent) :
  8. QMainWindow(parent),
  9. ui(new Ui::MainWindow)
  10. {
  11. ui->setupUi(this);
  12. // Create a data model for the mapping table from a CSV file
  13. csvModel = new QStandardItemModel(this);
  14. csvModel->setColumnCount(3);
  15. csvModel->setHorizontalHeaderLabels(QStringList() << "Марка" << "Модель" << "Цена");
  16. ui->tableView->setModel(csvModel);
  17.  
  18. // Open the file from the resources. Instead of the file
  19.     // Need to specify the path to your desired file
  20. QFile file(":/exampleTable.csv");
  21. if ( !file.open(QFile::ReadOnly | QFile::Text) ) {
  22. qDebug() << "File not exists";
  23. } else {
  24. // Create a thread to retrieve data from a file
  25. QTextStream in(&file);
  26. //Reads the data up to the end of file
  27. while (!in.atEnd())
  28. {
  29. QString line = in.readLine();
  30. // Adding to the model in line with the elements
  31. QList<QStandardItem *> standardItemsList;
  32. // consider that the line separated by semicolons into columns
  33. for (QString item : line.split(";")) {
  34. standardItemsList.append(new QStandardItem(item));
  35. }
  36. csvModel->insertRow(csvModel->rowCount(), standardItemsList);
  37. }
  38. file.close();
  39. }
  40. }
  41.  
  42. MainWindow::~MainWindow()
  43. {
  44. delete ui;
  45. delete csvModel;
  46. }

Download the archive with an example csv and QStandardItemModel

Do you like it? Share on social networks!

  • July 5, 2019, 7:04 p.m.

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?

TF
  • July 20, 2021, 11:21 p.m.

А если мне надо данными из файла подписать оси x и y и построить график как это сделать?

Evgenii Legotckoi
  • Oct. 11, 2021, 11:26 a.m.

Считайте данные из файла и постройте график, например с помощью библиотеки QCustomPlot

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…