QML与C++交互:在qml中使用QSqlQueryModel显示数据库数据

QML与C++交互:在qml中使用QSqlQueryModel显示数据库数据


本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.


参考链接:

http://qt-project.org/wiki/How_to_use_a_QSqlQueryModel_in_QML


环境:

主机:WIN7

开发环境:Qt5.2.1


说明:

在QML中不能直接对数据库进行操作,所以将QSqlQueryModel封装成子类,作为属性给QML使用


效果图:



源代码:


qml文件中负责数据托管显示的代码:

Component
        {
            id: msnDelegate
            Item
            {
                id: wrapper
                width: grid.cellWidth; height: grid.cellHeight
                Column
                {
                    Image{ source: "pics/light_on.png";anchors.horizontalCenter: parent.horizontalCenter; width: grid.cellWidth * 0.7; height: grid.cellHeight * 0.7}
                    Text { text: ctrl_id;anchors.horizontalCenter: parent.horizontalCenter; color: wrapper.GridView.isCurrentItem ? "red" :"blue" }
                    Text { text: name;anchors.horizontalCenter: parent.horizontalCenter; color: wrapper.GridView.isCurrentItem ? "red" :"blue" }
                }

                MouseArea
                {
                    anchors.fill: parent
                    onClicked: grid.currentIndex = index
                }
            }
        }
        GridView {
            id:grid
            //anchors.fill: parent
            width: parent.width
            height: parent.height - space1.height
            anchors {top: space1.bottom;}
            cellWidth: parent.width * 0.25
            cellHeight: parent.width * 0.25
            //model: listModel
            model: myFirstModel
            delegate: msnDelegate
            highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
            currentIndex: 2
            //focus: true
        }

C++代码:

sqlquerymodel.h

#ifndef SQLQUERYMODEL_H
#define SQLQUERYMODEL_H

#include <QSqlQueryModel>

class SqlQueryModel : public QSqlQueryModel
{
    Q_OBJECT

    void generateRoleNames();

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

    void setQuery(const QString &query, const QSqlDatabase &db = QSqlDatabase());
    void setQuery(const QSqlQuery &query);
    QVariant data(const QModelIndex &index, int role) const;

    virtual QHash<int, QByteArray> roleNames() const;

signals:

public slots:

};

#endif // SQLQUERYMODEL_H

sqlquerymodel.cpp

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

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

}

void SqlQueryModel::setQuery(const QString &query, const QSqlDatabase &db)
{
    QSqlQueryModel::setQuery(query,db);
    generateRoleNames();
}

void SqlQueryModel::setQuery(const QSqlQuery & query)
{
    QSqlQueryModel::setQuery(query);
    generateRoleNames();
}

void SqlQueryModel::generateRoleNames()
{
    QHash<int, QByteArray> roleNames;
    for( int i = 0; i < record().count(); i++) {
        roleNames[Qt::UserRole + i + 1] = record().fieldName(i).toUtf8();
    }
    //setRoleNames(roleNames);
}

QHash<int, QByteArray> SqlQueryModel::roleNames() const
{
    QHash<int, QByteArray> roleNames;
    for( int i = 0; i < record().count(); i++) {
        roleNames[Qt::UserRole + i + 1] = record().fieldName(i).toUtf8();
    }
    return roleNames;
}

QVariant SqlQueryModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QSqlQueryModel::data(index, role);
    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;
}

主函数中 数据关联的代码:
    SqlQueryModel *model1 = new SqlQueryModel(0);
    model1->setQuery("SELECT * FROM ctrl_para");

    QtQuick2ApplicationViewer viewer;

    viewer.rootContext()->setContextProperty("myFirstModel", model1);

    viewer.setMainQmlFile(QStringLiteral("qml/SH_User/base.qml"));
    viewer.showExpanded();

注意:

query操作只执行一次,所以要想实时显示数据库中的数据,可以定时读取数据库以动态显示数据


  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
QMLC++ 交互的过程一般分为以下几个步骤: 1. 定义 C++ 类并注册到 QML 你需要在 C++ 定义一个类,该类封装了你想要实现的功能。同时,你需要使用 `qmlRegisterType` 函数将该类注册到 QML ,以便在 QML 使用该类。 例如,你可以定义一个名为 `MyClass` 的类,并将其注册到 QML : ```cpp class MyClass : public QObject { Q_OBJECT public: Q_INVOKABLE int myFunction(int arg) { // 实现你的功能 } }; qmlRegisterType<MyClass>("com.example", 1, 0, "MyClass"); ``` 在上面的代码,`Q_INVOKABLE` 用于声明 `myFunction` 函数可从 QML 调用,`qmlRegisterType` 函数用于将 `MyClass` 类注册到 QML 。`"com.example"` 表示注册的命名空间,`1` 和 `0` 表示主版本号和次版本号,`"MyClass"` 是在 QML 使用的类名。 2. 在 QML 使用 C++ 类 在 QML 使用 C++ 类时,你需要使用 `import` 语句导入该类所在的命名空间。然后,你可以通过该命名空间来访问该类。例如: ```qml import com.example 1.0 MyClass { id: myClass } Button { onClicked: { var result = myClass.myFunction(42) // 处理返回值 } } ``` 在上面的代码,`import` 语句用于导入 `com.example` 命名空间,`MyClass` 用于创建一个 `MyClass` 实例,`id` 属性用于设置实例的标识符,`Button` 用于创建一个按钮,`onClicked` 事件处理程序调用了 `myFunction` 函数,并处理了它的返回值。 3. 在 C++ 访问 QML 的对象 如果你需要从 C++ 访问 QML 的对象,你可以使用 `QQuickItem` 类提供的 `findChild` 函数。例如: ```cpp QQuickItem *item = qmlEngine.rootObjects().value(0)->findChild<QQuickItem*>("myItem"); if (item) { // 处理 item 对象 } ``` 在上面的代码,`qmlEngine.rootObjects()` 函数返回 QML 引擎所有的根对象,`value(0)` 返回第一个根对象,`findChild` 函数用于查找名为 `"myItem"` 的子对象。 以上就是 QMLC++ 交互的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值