c++ - SqlQueryModel 通用模型 - 角色名称设置不正确

标签 c++ qt sqlite qml

我一直在尝试使用 qt 文档中的 SqlQueryModel 通用模型,但我似乎无法让它与 qml 一起正常工作。 与我在 Stack OverFlow 上看到的另一个问题非常相似,但他们也没有得到答案 My QSqlQueryModel doesn't show data in the listview

我可以查询数据库并在我的 ListView 中获得正确数量的结果,但是如果我尝试通过 RoleName 访问一个属性,那么它会说该属性未定义

    main.cpp
    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QtQml>
    #include "wordmodel.h"

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

        WordModel *wordListModel = new WordModel( qApp);

        engine.rootContext()->setContextProperty("WLModel", wordListModel);
        engine.load(QUrl(QStringLiteral("qrc:///qml/main.qml")));

        return app.exec();
    }

SqlQueryModel.h

    #ifndef SQLQUERYMODEL_H
    #define SQLQUERYMODEL_H

    #include <QSqlQueryModel>
    #include <QHash>
    #include <QByteArray>

    class SqlQueryModel : public QSqlQueryModel
    {
        Q_OBJECT
        QVariant data(const QModelIndex &index, int role=Qt::DisplayRole ) const;
        inline RoleNameHash roleNames() const { return *roles; }

    public:
        explicit SqlQueryModel(QObject *parent = 0);

        Q_INVOKABLE void setQuery(const QString &query, const QSqlDatabase &db = QSqlDatabase());
        Q_INVOKABLE void setQuery();
        QHash<int, QByteArray> generateRoleNames();
        //inline RoleNameHash roleNames() const { return *roles; }
        QHash<int, QByteArray> roleNames() const{return roles;}

    signals:
        void countChanged();

    public slots:
        void connectToDb();
        void closeDB();

    private:
        //QSqlQuery SQL_SELECT;
        QHash<int, QByteArray> roles;
        QSqlDatabase mydb;

    };


    #endif // SQLQUERYMODEL_H

SqlQueryModel.cpp

    #include "sqlquerymodel.h"
    #include <QSqlRecord>
    #include <QSqlField>
    #include <QDebug>

    SqlQueryModel::SqlQueryModel(QObject *parent) :
        QSqlQueryModel(parent)
    {
        mydb=QSqlDatabase::addDatabase("QSQLITE");
        QString dbPath = "E://Qt//sqlite//dictionary.db";
        mydb.setDatabaseName(dbPath);
        mydb.setUserName("admin");
        mydb.setPassword("admin");
    }

    void SqlQueryModel::connectToDb()
    {
        if(!mydb.open())
        {
            qDebug() << "Database didnt open";
        }
        else
        {
            qDebug() << "Your database is open";
        }
    }

    void SqlQueryModel::closeDB()
    {
        mydb.close();
    }

    void SqlQueryModel::setQuery(const QString &query, const QSqlDatabase &db)
    {
        connectToDb();
        QSqlQueryModel::setQuery("SELECT * FROM words_en WHERE word LIKE 'young%' LIMIT 10",mydb);
        generateRoleNames();
        closeDB();
    }

    void SqlQueryModel::setQuery()
    {
        connectToDb();
        QSqlQueryModel::setQuery("SELECT * FROM words_en WHERE word LIKE 'young%' LIMIT 10");
        generateRoleNames();
        closeDB();
    }


    QHash<int, QByteArray> SqlQueryModel::generateRoleNames()
    {
        roles.clear();
        for( int i = 0; i < record().count(); i++) {
            roles[Qt::UserRole + i + 1] = record().fieldName(i).toLatin1();
            qDebug() << roles[Qt::UserRole + i + 1];

        }
       return roles;
    }

    QVariant SqlQueryModel::data(const QModelIndex &index, int role) const
    {
        qDebug() << "ALALLALALALALALA";
        QVariant value = QSqlQueryModel::data(index, role);
        qDebug() << value;
        if(role < Qt::UserRole)
        {
            value = QSqlQueryModel::data(index, role);
        }
        else
        {
            int columnIdx = role - Qt::UserRole - 1;
            QModelIndex modelIndex = this->index(index.row(), columnIdx);
            value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
        }
        return value;
    }

main.qml

import QtQuick 2.2
import QtQuick.Window 2.1

Window {
    visible: true
    width: 800
    height: 800

    // here i tried putting the class into a Qml type with the qmlRegisterType()
    // but also to no avail

//    SqlQueryModel{
//        id:something
//        Component.onCompleted: {
//            something.setQuery()
//        }
//    }

    ListView{
        width:parent.width
        height:parent.height
        model:wordListModel
        delegate: Item{
            width:parent.width
            height: width/10
            Text {
                id: name
                text: word
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
                anchors.fill:parent
                Component.onCompleted: {
                    console.log(id)
                    console.log(word)
                }
            }
        }
    }
}

最佳答案

您使用的是哪个版本的Qt。方法 generateRoleNames() 已被弃用,重新实现 roleNames() 而不是 generateRoleNames()

关于c++ - SqlQueryModel 通用模型 - 角色名称设置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427491/

相关文章:

java - java中的数组结构

android - 在 SQLite DatabaseErrorHandler 中需要做什么

java - Android 从数据库中保存和检索对象

python - 使用数据框在 sqlite 中创建表

c++ - 为什么 std::is_function<T> 会导致编译错误?

c++ - Python 的 xml.etree.ElementTree 相当于 C++ XML 库

c++ - 将 Curiously Recurring Template Pattern (CRTP) 与其他类型参数一起使用

windows - 何时或如何删除 Qt 中的 QThread

c++ - 无法使用 QGLWidget 编译 Qt

c++ - 分配给嵌套的 QVariantMap