SqlQueryModel通用模型-角色名称没有正确设置

SqlQueryModel generic model - Role Names not setting right

本文关键字:设置 模型 角色 SqlQueryModel      更新时间:2023-10-16

我一直试图从qt文档中使用SqlQueryModel通用模型,但我似乎无法让它与qml正常工作。与我在Stack OverFlow上看到的另一个问题非常相似,但他们也没有得到答案我的QSqlQueryModel没有显示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()