ListView QML的roleName中的QSqlQueryModel引用错误

QSqlQueryModel reference error in roleName for ListView QML(ListView QML的roleName中的QSqlQueryModel引用错误)
本文介绍了ListView QML的roleName中的QSqlQueryModel引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的 SQlite 数据库中获取模型,当我在 QSqlQueryModel 中设置查询时,我可以获得行数、列数等.但是每列中的数据我有一个 ReferenceError 试图获取列名cpp代码:

I want to get the model from my SQlite Database, when I set the query in the QSqlQueryModel I can get the number of rows, number of columns, etc. But the data inside each column I have a ReferenceError trying to get the name of the column The cpp code:

//data base users
QSqlQueryModel *sqlModel = new QSqlQueryModel();
sqlModel->setQuery("SELECT usuarios.nombre FROM usuarios");

sqlModel->setHeaderData(0,Qt::Horizontal, QObject::tr("nombre"));
qDebug() << "ROL: " << sqlModel->roleNames();
qDebug() << "number of rows: " << sqlModel->rowCount();
qDebug() << "number of columns: " << sqlModel->columnCount();
qDebug() << "HEADER: " << sqlModel->headerData(1, Qt::Horizontal).toString();

这就是我从输出中得到的

And this is what I get from the output

这就是我在 QML 中的 ListView 中的内容:

This is what I have in my ListView in QML:

ListView {
    id: listaUsuarios
    model: sqlModel
    delegate:
    Text{
        anchors.fill: parent
        text: nombre
     }
}

推荐答案

如何观察表的字段不是角色,所以不能从QML访问,所以要访问,字段的名字必须是添加为角色,为此必须覆盖该类:

How to observe the fields of the table are not roles, so they can not be accessed from QML, so to be accessed, the name of the fields must be added as a role, for this the class must be overwritten:

class SqlQueryModel: public QSqlQueryModel{
public:
    using QSqlQueryModel::QSqlQueryModel;
    QVariant data(const QModelIndex &index, int role) const
    {
        QVariant value;
        if (index.isValid()) {
            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;
    }
    QHash<int, QByteArray> roleNames() const
    {
        QHash<int, QByteArray> roles = QSqlQueryModel::roleNames();
        for (int i = 0; i < this->record().count(); i ++) {
            roles.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
        }
        return roles;
    }
};

例子:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QDebug>

static bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if (!db.open()) {
        qDebug()<<"Unable to establish a database connection.
"
                  "This example needs SQLite support. Please read "
                  "the Qt SQL driver documentation for information how "
                  "to build it.

"
                  "Click Cancel to exit.";
        return false;
    }

    QSqlQuery query;
    query.exec("create table usuarios (ID INTEGER PRIMARY KEY AUTOINCREMENT, "
               "nombre VARCHAR(20), apellido VARCHAR(20))");
    query.exec("insert into usuarios values(1, 'Danny', 'Young')");
    query.exec("insert into usuarios values(2, 'Christine', 'Holand')");
    query.exec("insert into usuarios values(3, 'Lars', 'Gordon')");
    query.exec("insert into usuarios values(4, 'Roberto', 'Robitaille')");
    query.exec("insert into usuarios values(5, 'Maria', 'Papadopoulos')");
    return true;
}

class SqlQueryModel: public QSqlQueryModel{
public:
    using QSqlQueryModel::QSqlQueryModel;
    QVariant data(const QModelIndex &index, int role) const
    {
        QVariant value;
        if (index.isValid()) {
            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;
    }
    QHash<int, QByteArray> roleNames() const
    {
        QHash<int, QByteArray> roles = QSqlQueryModel::roleNames();
        for (int i = 0; i < this->record().count(); i ++) {
            roles.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
        }
        return roles;
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    if(!createConnection())
        return -1;

    SqlQueryModel sqlModel;
    sqlModel.setQuery("SELECT usuarios.nombre FROM usuarios");
    qDebug() << sqlModel.roleNames();

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("sqlModel", &sqlModel);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

输出:

这篇关于ListView QML的roleName中的QSqlQueryModel引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
Window functions not working in pd.read_sql; Its shows error(窗口函数在pd.read_sql中不起作用;它显示错误)
(Closed) Leaflet.js: How I can Do Editing Geometry On Specific Object I Select Only?((已关闭)Leaflet.js:如何仅在我选择的特定对象上编辑几何图形?)
in sqlite update trigger with multiple if/Case Conditions(在具有多个IF/CASE条件的SQLite UPDATE触发器中)
Android: Why is Room so slow?(Android:为什么Room这么慢?)
Remote Procedure call failed with sql server 2008 R2(使用 sql server 2008 R2 的远程过程调用失败)