Advanced search

QtQt/C++ - Lesson 006. QSqlQueryModel – Tables in Qt with SQL-query

Using QSqlQueryModel to form tables in Qt is the most hardcore version with the lowest level of abstraction than the use QSqlTableModel or QSqlRelationalTableModel . But with all this, and the most flexible option, which requires a deeper knowledge of the language of SQL-queries. In a previous article , two tables were constructed:

  • The main, which were columns Дата, Время, Имя Хоста, IP-адрес.
  • Table devices , which were columns Имя Хоста and IP-адрес.

In the main table in the columns of the host name and IP-address points ID-devices, which carried out a substitution of data from the device tables. In this paper, the structure of the first table and therefore the table will look different:

  • The main, which were columns Дата, Время, ID устройства.
  • Table devices , which were columns Имя Хоста and IP-адрес.

The Generating of the main table in the Application will be SQL-query and the table will be a column respectively Дата, Время, Имя Хоста and IP-адрес.

QtQt/C++ - Lesson 005. QSqlRelationalTableModel - The work with relational tables

In Qt to represent table fields, which involve foreign keys to other tables database, QSqlRelationalTableModel can be used, which is a more advanced version QSqlTableModel class, which was considered in the previous article .

This class allows you to set relationships between tables and substitute values in the representation of the table formed by the values of the connected tables.

This article discusses the option of two tables. One table contains information about the devices (host name and IP address), and the second table ID of the device, which in the second table to be substituted host name and IP address of the device, respectively.

Project Structure for QSqlRelationalTableModel

Структура проекта

The project for this tutorial is a modified version of the preceding Article and remains unchanged.

QtQt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

In order to present the information in a database table we can to use the following classes:

  • QSqlQueryModel - model that generates a table by defining the raw SQL-query. It may be useful in the formation of a special custom filters and compile information from various database tables. About it in more detail in later lessons.
  • QSqlTableModel - the subject of our discussion in this article. The model that generates the table from database using name of table. But we can to create table without information from other tables.
  • QSqlRelationalTableModel - a class that allows you to create a table with constraints from other tables, substituting the values of the table, which is the model on contained in other tables record ID.

For comfortable work with information that is placed in the database applied additional class, which partially constitutes a "facade" design pattern.

Project structure for QSqlTableModel

he project is created as an application Qt Widgets, and it contains the following files:

  • - project profile;
  • mainwindow.h - header file of mainwindow;
  • mainwindow.cpp - source file of mainwindow;
  • main.cpp - file with main function;
  • mainwindow.ui - interface of mainwindow;
  • database.h - header file of helper class to be used for information that is placed in a database;
  • database.cpp - source file of helper class to be used for information that is placed in a database;
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it

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


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
May 25, 2020, 11:33 a.m.
Mitja Nagibin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
May 25, 2020, 5:05 a.m.

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

  • Result:66points,
  • Rating points-1
May 25, 2020, 3:30 a.m.
just maks

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
Last comments
May 26, 2020, 6:51 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

У вас база данных не открылась Исправьте путь к базе данных на свой корректный в следующих методах void DataBase::connectToDataBase() bool DataBase::openDataBase()
May 26, 2020, 6:22 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

полностью повторил структору проекта. В форму дабавил tableView. Но при запуске получаю форму только с пустым tableView. Можете подсказать в чем пробелма?
May 26, 2020, 6:02 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

Потому что это файл который нужно создать, а не библиотека. В статье есть содержание этого файла. Добавляйте в проект. Копируйте содержимое из статьи.
May 26, 2020, 6 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

не удается подключиить библеотеку include "database.h" выдает ошибку. Можете помочь?
Now discuss on the forum
May 26, 2020, 5:16 a.m.

Отсутствие драйвера SQLite в пакете Qt 4 на Linux

Вот честно непонимаю почему до сих пор используют qt4, там же столько всего отсутствует, много фишек и возможностей нету там. То есть используя такое старье приходится много писать самому а не и…
May 26, 2020, 2:24 a.m.
Dzhon Kofi

Disable autoscroll

такие естественные решения все перепробовал. Получилось вчера так: const int maximumScroll = ui->_samples->verticalScrollBar()->maximum();const int sliderPos = ui->_samp…
May 26, 2020, 12:43 a.m.
Ruslan Polupan

Посоветуйте новичку (базы данных и Qt, что учить)

Без БД сейчас практически никуда. Поэтому SQL надо знать. SQLite самы простой вариант, но имхо лучще начать с бд клиент-сервер. Настроить сервер. Подключаться клиентом. Просто это помогает понят…
May 25, 2020, 2:42 p.m.
Esteban José María

Компиляция пустого проекта Qt Android

qt 5.12.8 BUILD SUCCESSFUL in 42s 28 actionable tasks: 28 executed Android package built successfully in 68.251 ms. Ну, буду разбираться по-тихоньку. :)
May 25, 2020, 1:24 p.m.

Использование файлов в памяти (memory file mapping)

Добрый вечер, проблемы работы с файлом Exel нет вообще. Весь смысл в том чтобы не создавать на диске физический файл (требования безопасности), дабы потом не чистить. А так вопрос только в этом …
© EVILEG 2015-2020
Recommend hosting TIMEWEB