Evgenii Legotckoi
Evgenii LegotckoiNov. 5, 2015, 3:26 a.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.

TEMPLATE = app

QT += qml quick widgets sql

SOURCES += main.cpp \
    database.cpp \
    model.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

HEADERS += \
    database.h \
    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.

#ifndef DATABASE_H
#define DATABASE_H

#include <QObject>
#include <QSql>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlDatabase>
#include <QFile>
#include <QDate>
#include <QDebug>

#define DATABASE_HOSTNAME   "ExampleDataBase"
#define DATABASE_NAME       "DataBase.db"

#define TABLE                   "TableExample"
#define TABLE_DATE              "date"
#define TABLE_TIME              "time"
#define TABLE_MESSAGE           "message"
#define TABLE_RANDOM            "random"

class DataBase : public QObject
{
    Q_OBJECT
public:
    explicit DataBase(QObject *parent = 0);
    ~DataBase();
    /* Methods to work directly with the class. 

database.cpp

#include "database.h"

DataBase::DataBase(QObject *parent) : QObject(parent)
{
    this->connectToDataBase();
    /* 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.

#ifndef MODEL_H
#define MODEL_H

#include <QObject>
#include <QSqlQueryModel>

class Model : public QSqlQueryModel
{
    Q_OBJECT
public:
    // List all the roles that will be used in the TableView
    enum Roles {
        DateRole = Qt::UserRole + 1,    
        TimeRole,                       
        RandomRole,                    
        MessageRole                     
    };

    explicit Model(QObject *parent = 0);

    // Override the method that will return the data
    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;

protected:
    /* hashed table of roles for speakers. 
     * The method used in the wilds of the base class QAbstractItemModel, 
     * from which inherits the class QSqlQueryModel
     * */
    QHash<int, QByteArray> roleNames() const;

signals:

public slots:
};

#endif // MODEL_H

model.cpp

#include "model.h"

Model::Model(QObject *parent) :
    QSqlQueryModel(parent)
{

}

// The method for obtaining data from the model
QVariant Model::data(const QModelIndex & index, int role) const {

    // Define the column number, address, so to speak, on the role of number
    int columnId = role - Qt::UserRole - 1;
    // Create the index using the ID column
    QModelIndex modelIndex = this->index(index.row(), columnId);

    /* And with the help of already data() method of the base class 
     * to take out the data table from the model
     * */
    return QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}

QHash<int, QByteArray> Model::roleNames() const {

    QHash<int, QByteArray> roles;
    roles[DateRole] = "date";
    roles[TimeRole] = "time";
    roles[RandomRole] = "random";
    roles[MessageRole] = "message";
    return roles;
}

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.

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <database.h>
#include <model.h>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine;

    // Initialize database
    DataBase database;
    // We declare and initialize the data model representation
    Model *model = new Model();
    /* Since we inherited from QSqlQueryModel, the data sample, 
     * we need to perform SQL-query in which we select all the needed fields from the desired table to us
     * */
    model->setQuery("SELECT " TABLE_DATE ", " TABLE_TIME ", " TABLE_RANDOM ", " TABLE_MESSAGE
                   " FROM " TABLE);

    /* And it is already familiar from the lessons of the signals and slots in QML. 
     * We put the resulting model in QML context to be able to refer to the model name "myModel"
     * */
    engine.rootContext()->setContextProperty("myModel", model);

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

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".

import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TableView {
        anchors.fill: parent

        TableViewColumn {
            role: "date"    // These roles are roles names coincide with a C ++ model
            title: "Date"
        }

        TableViewColumn {
            role: "time"    // These roles are roles names coincide with a C ++ model
            title: "Time"
        }

        TableViewColumn {
            role: "random"  // These roles are roles names coincide with a C ++ model
            title: "Random"
        }

        TableViewColumn {
            role: "message" // These roles are roles names coincide with a C ++ model
            title: "Message"
        }

        // We set the model in the TableView
        model: myModel
    }
}

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

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.

Do you like it? Share on social networks!

AK
  • Nov. 1, 2020, 4:56 a.m.
  • (edited)

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

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

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

R
  • June 17, 2023, 4:15 a.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 2:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks