3

I would like to call data from my local database (diaBaneData.db) into a TableView in QML. But I am struggeling with the c++ part right now.

There is no problem with the output of my database with the "model"-Version from main.cpp. When using the "model2" version nothing except the headline will be shown in the QTableView. As the c++ version isn't working the qml-tableview is empty, too.

I think there must be something wrong about the roles/fieldnames but I can't find out whats wrong.

In the output there will be printed several lines saying: QSqlQuery::value: unknown field name ''!

main.cpp

    #include <QApplication>
    #include <QQmlApplicationEngine>
    #include "QTableView"
    #include "mysqlmodel.h"

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

        // Create the database Table inside is named "diaBaneDatabase"
        QSqlDatabase m_Database;
        m_Database = QSqlDatabase::addDatabase("QSQLITE");
        m_Database.setDatabaseName("C:/Users/blade/Desktop/diaBaneData.db");
        if (!m_Database.open()) {
            qDebug("ERROR");
        }

        // This is how my table will correctly displayed
        QSqlQueryModel* model = new QSqlQueryModel;
        model->setQuery("SELECT * FROM diaBaneDatabase");

        // Using my own class -> nothing will be shown exepct the headline
        QSqlQueryModel* model2 = new MySqlModel();
        model2->setQuery("SELECT * FROM diaBaneDatabase");

        QTableView *view = new QTableView;
        view->setModel(model2);
        view->show();

        qmlRegisterType<MySqlModel>("MySqlModel", 1, 0, "MySqlModel");

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

        return app.exec();
    }

mysqlmodel.h

    #ifndef MYSQLMODEL_H
    #define MYSQLMODEL_H

    #include <QtSql>
    #include <QSqlQuery>

    class MySqlModel: public QSqlQueryModel
    {
        Q_OBJECT
    public:
        MySqlModel(QObject *parent = 0) : QSqlQueryModel(parent) {}

        enum Roles {
            id = Qt::UserRole + 1,
            dateAndTime,
            bloodSugar,
            eatenKE,
            jubinDextro
        };

        QHash<int, QByteArray> roleNames() const {
            QHash<int, QByteArray> roles;
            roles[id] = "idRole";
            roles[dateAndTime] = "dateAndTimeRole";
            roles[bloodSugar] = "bloodSugarRole";
            roles[eatenKE] = "eatenKERole";
            roles[jubinDextro] = "jubinDextroRole";
            return roles;
        }

        QVariant data(const QModelIndex &index, int role) const {
            if (!index.isValid())
                return QVariant();

            QString fieldName;
            switch (role) {
                case id: fieldName = QStringLiteral("diaBaneDatabase.id"); break;
                case dateAndTime: fieldName = QStringLiteral("diaBaneDatabase.dateAndTime"); break;
                case bloodSugar: fieldName = QStringLiteral("diaBaneDatabase.bloodSugar"); break;
                case eatenKE: fieldName = QStringLiteral("diaBaneDatabase.eatenKE"); break;
                case jubinDextro: fieldName = QStringLiteral("diaBaneDatabase.jubinDextro"); break;
            }
            if (!this->record().isGenerated(fieldName))
                return QVariant();
            else {
                QModelIndex item = indexInQuery(index);
                if ( !this->query().seek(item.row()) )
                    return QVariant();
                return this->query().value(fieldName);
            }
            return QVariant();
        }
    };

    #endif // MYSQLMODEL_H

main.qml

    import QtQuick 2.5
    import QtQuick.Controls 1.4
    import MySqlModel 1.0

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

        menuBar: MenuBar {
            Menu {
                title: qsTr("File")
                MenuItem {
                    text: qsTr("&Open")
                    onTriggered: console.log("Open action triggered");
                }
                MenuItem {
                    text: qsTr("Exit")
                    onTriggered: Qt.quit();
                }
            }
        }

        MySqlModel{
            id: sqlTableModel
        }

        TableView{
            id: tableviewTTT
            width: 600
            height: 400
                    TableViewColumn{ role: "idRole" ; title: "ID" ; visible: true}
                    TableViewColumn{ role: "dateAndTimeRole" ; title: "DateAndTime" }
                    TableViewColumn{ role: "bloodSugarRole" ; title: "BloodSugar" }
                    TableViewColumn{ role: "eatenKERole" ; title: "EatenKE" }
                    TableViewColumn{ role: "jubinDextroRole" ; title: "JubinDextro" }

            model: sqlTableModel
        }
    }

db-File: Database

jpnurmi
  • 5,716
  • 2
  • 21
  • 37
F-Kae
  • 155
  • 1
  • 2
  • 14
  • Did you try to debug it? What value contains `fieldName` when you call to `query().value(fieldName)`? May be it empty in fact? – folibis Jul 31 '16 at 09:34
  • If I ad this line: `qDebug() << "fieldname:' " << fieldName << "' role: '" << role << "'" << "id would be: '" << id << "'";` to the else part of the data function the out put is: `fieldname:' "" ' role: ' 6 ' id would be: ' 257 ' fieldname:' "" ' role: ' 7 ' id would be: ' 257 ' fieldname:' "" ' role: ' 9 ' id would be: ' 257 ' fieldname:' "" ' role: ' 10 ' id would be: ' 257 ' fieldname:' "" ' role: ' 1 ' id would be: ' 257 ' fieldname:' "" ' role: ' 0 ' id would be: ' 257 ' fieldname:' "" ' role: ' 8 ' id would be: ' 257 '` – F-Kae Jul 31 '16 at 10:33
  • so you see the problem - `fieldName` is empty and query() returns you error. – folibis Jul 31 '16 at 10:55
  • Ok I see the Problem but I don't know why it's searching for roles in between 0-10 and my roles are defined from 257-261. I don't really understand the background of this. My class is some kind of copy, paste and a little editing by myself. – F-Kae Jul 31 '16 at 11:00
  • I don't get the point thats missing to fix my error. I would be very glad if someone can give me further hints. – F-Kae Jul 31 '16 at 18:38

0 Answers0