Evgenii Legotckoi
Nov. 5, 2015, 2:26 p.m.

QML - Lesson 011. Data transmission from QML QSqlQueryModel in the TableView

To represent database tables in the development TableView using QML You can use a class inherited from QSqlQueryModel . To do this, in the inherited class to define a method that would establish the respective roles of the table columns to the corresponding columns in the TableView, defined in the QML , which also indicates the roles of each object TableViewColumn , that is, for each column. You will also need to override a method QVariant data(...) const , which returns the data for the table cells. In this case, the information will be returned in accordance with certain roles columns of the table.

The project structure to work with TableView

The project consists of the following files:

  • QmlSqlQueryModel.pro - the profile of the project;
  • database.h - header to create and initialize the test database;
  • database.cpp - file source code to create and initialize the test database;
  • model.h - header data model file;
  • model.cpp - file source data model;
  • main.cpp - the main source file;
  • main.qml - qml file TableView.

QmlSqlQueryModel.pro

Be sure to connect the SQL module to the project in this file. Otherwise QSqlQueryModel library will not be found when compiling the project.

  1. TEMPLATE = app
  2.  
  3. QT += qml quick widgets sql
  4.  
  5. SOURCES += main.cpp \
  6. database.cpp \
  7. model.cpp
  8.  
  9. RESOURCES += qml.qrc
  10.  
  11. # Additional import path used to resolve QML modules in Qt Creator's code model
  12. QML_IMPORT_PATH =
  13.  
  14. # Default rules for deployment.
  15. include(deployment.pri)
  16.  
  17. HEADERS += \
  18. database.h \
  19. model.h

database.h

Header wrapper class file to initialize the database connection, and its creation if the database does not exist. This helper class appeared in a number of earlier lessons. For example, when working QSqlTableModel or QSqlRelationalTableModel . So I will not focus on it, and only give the code. And I note that this class is created or opened (if already created) database which is placed at each opening four lines. And each row consists of four columns: date ( "date") , the time ( "time") , pseudo-random number ( "random") , and reports of a given number ( "message").

ATTENTION!!! - The database file is created in the folder C: / example, so the correct method or DataBase::connectToDataBase() example or create a folder on drive C.

  1. #ifndef DATABASE_H
  2. #define DATABASE_H
  3.  
  4. #include <QObject>
  5. #include <QSql>
  6. #include <QSqlQuery>
  7. #include <QSqlError>
  8. #include <QSqlDatabase>
  9. #include <QFile>
  10. #include <QDate>
  11. #include <QDebug>
  12.  
  13. #define DATABASE_HOSTNAME "ExampleDataBase"
  14. #define DATABASE_NAME "DataBase.db"
  15.  
  16. #define TABLE "TableExample"
  17. #define TABLE_DATE "date"
  18. #define TABLE_TIME "time"
  19. #define TABLE_MESSAGE "message"
  20. #define TABLE_RANDOM "random"
  21.  
  22. class DataBase : public QObject
  23. {
  24. Q_OBJECT
  25. public:
  26. explicit DataBase(QObject *parent = 0);
  27. ~DataBase();
  28. /* Methods to work directly with the class.

database.cpp

  1. #include "database.h"
  2.  
  3. DataBase::DataBase(QObject *parent) : QObject(parent)
  4. {
  5. this->connectToDataBase();
  6. /* After that is done filling the database tables of

model.h

And now the most interesting. Inheriting from class QSqlQueryModel and create your own model class that returns data in accordance with certain roles in the columns in the TableView Qml layer. That is, override the method to retrieve the data - this data() method, as well as roleNames() method that returns the role names under which data will be substituted in the TableView , I note that the names will be the same.

  1. #ifndef MODEL_H
  2. #define MODEL_H
  3.  
  4. #include <QObject>
  5. #include <QSqlQueryModel>
  6.  
  7. class Model : public QSqlQueryModel
  8. {
  9. Q_OBJECT
  10. public:
  11. // List all the roles that will be used in the TableView
  12. enum Roles {
  13. DateRole = Qt::UserRole + 1,
  14. TimeRole,
  15. RandomRole,
  16. MessageRole
  17. };
  18.  
  19. explicit Model(QObject *parent = 0);
  20.  
  21. // Override the method that will return the data
  22. QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
  23.  
  24. protected:
  25. /* hashed table of roles for speakers.
  26.   * The method used in the wilds of the base class QAbstractItemModel,
  27.   * from which inherits the class QSqlQueryModel
  28. * */
  29. QHash<int, QByteArray> roleNames() const;
  30.  
  31. signals:
  32.  
  33. public slots:
  34. };
  35.  
  36. #endif // MODEL_H

model.cpp

  1. #include "model.h"
  2.  
  3. Model::Model(QObject *parent) :
  4. QSqlQueryModel(parent)
  5. {
  6.  
  7. }
  8.  
  9. // The method for obtaining data from the model
  10. QVariant Model::data(const QModelIndex & index, int role) const {
  11.  
  12. // Define the column number, address, so to speak, on the role of number
  13. int columnId = role - Qt::UserRole - 1;
  14. // Create the index using the ID column
  15. QModelIndex modelIndex = this->index(index.row(), columnId);
  16.  
  17. /* And with the help of already data() method of the base class
  18.   * to take out the data table from the model
  19. * */
  20. return QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
  21. }
  22.  
  23. QHash<int, QByteArray> Model::roleNames() const {
  24.  
  25. QHash<int, QByteArray> roles;
  26. roles[DateRole] = "date";
  27. roles[TimeRole] = "time";
  28. roles[RandomRole] = "random";
  29. roles[MessageRole] = "message";
  30. return roles;
  31. }

main.cpp

And now, using the techniques of registration refer to C ++ object in QML layer of the lesson on the signals and slots in QML register a custom data model in QML as the layer properties that can be accessed by the name "myModel" from QML layer. Not forgetting, of course perform SQL-query to retrieve data.

  1. #include <QApplication>
  2. #include <QQmlApplicationEngine>
  3. #include <QQmlContext>
  4.  
  5. #include <database.h>
  6. #include <model.h>
  7.  
  8. int main(int argc, char *argv[])
  9. {
  10. QApplication app(argc, argv);
  11. QQmlApplicationEngine engine;
  12.  
  13. // Initialize database
  14. DataBase database;
  15. // We declare and initialize the data model representation
  16. Model *model = new Model();
  17. /* Since we inherited from QSqlQueryModel, the data sample,
  18.   * we need to perform SQL-query in which we select all the needed fields from the desired table to us
  19. * */
  20. model->setQuery("SELECT " TABLE_DATE ", " TABLE_TIME ", " TABLE_RANDOM ", " TABLE_MESSAGE
  21. " FROM " TABLE);
  22.  
  23. /* And it is already familiar from the lessons of the signals and slots in QML.
  24.   * We put the resulting model in QML context to be able to refer to the model name "myModel"
  25. * */
  26. engine.rootContext()->setContextProperty("myModel", model);
  27.  
  28. engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
  29.  
  30. return app.exec();
  31. }

main.qml

And the simplest example of all - is to install TableView a column that the roles, which will be replaced with the data, as well as to establish the model itself by the registered name "myModel".

  1. import QtQuick 2.5
  2. import QtQuick.Controls 1.4
  3.  
  4. ApplicationWindow {
  5. visible: true
  6. width: 640
  7. height: 480
  8. title: qsTr("Hello World")
  9.  
  10. TableView {
  11. anchors.fill: parent
  12.  
  13. TableViewColumn {
  14. role: "date" // These roles are roles names coincide with a C ++ model
  15. title: "Date"
  16. }
  17.  
  18. TableViewColumn {
  19. role: "time" // These roles are roles names coincide with a C ++ model
  20. title: "Time"
  21. }
  22.  
  23. TableViewColumn {
  24. role: "random" // These roles are roles names coincide with a C ++ model
  25. title: "Random"
  26. }
  27.  
  28. TableViewColumn {
  29. role: "message" // These roles are roles names coincide with a C ++ model
  30. title: "Message"
  31. }
  32.  
  33. // We set the model in the TableView
  34. model: myModel
  35. }
  36. }

Coclusion

As a result of the above actions you will receive an application in which the window is TableView data taken out of the database, as shown in the figure.

Video

Do you like it? Share on social networks!

AK
  • Nov. 1, 2020, 3:56 p.m.
  • (edited)

Добрый день.
Можно ли как то вставить картинку в TableView? Допустим в бд есть boolean столбец который говорит нам добавлен ли объект в избранное, как можно исходя из данных этого поля отобразить ту или иную иконку в TableView?
Пробовал так хотя бы отобразить иконку в 1 колонке добавив в data()

  1. if ( role==FavRole && index.column() == 0) {
  2. return QIcon("D:/Users/Downloads/ico.ico");
  3. }

Но иконка вставляется текстом

R
  • June 17, 2023, 2:15 p.m.

Ну что, ты разобрался?

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • 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, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup