在QML对象和C++之间传递二维数组
某些 C++ 序列类型在 QML 中被显式地作为 JavaScript 数组类型支持。
QML当前支持如下类型:
QList<int>
QList<qreal>
QList<bool>
QList<QString>
andQStringList
QList<QUrl>
这些序列类型都直接在底层的 C++ 程序来实现的。有两种方法可以把这样的序列类型在 QML 和 C++ 之间相互暴露:使用 Q_PROPERTY
修饰序列类型或使用 Q_INVOKABLE
方法。
下面的方法演示从 QML 中传递如何传递一维数组和二维数组到 C++ 中。
创建一个
AppModel
类,这个模型作为应用程序的数据模型,在 QML 和 C++ 之间交互。class AppModel : public QObject { Q_OBJECT public: explicit AppModel(QObject *parent = 0); ... };
使用
qmlRegisterType()
函数把AppModel
暴露到 QML UI 层(需在QML文件加载前注册)。#include <QGuiApplication> #include <QQmlApplicationEngine> #include <appmodel.h> #include <QtQml> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qmlRegisterType<AppModel>("com.mycompany.qmlcomponents", 1, 0, "AppModel"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
在 QML 文件中实例化
AppModel
。import QtQuick 2.4 import QtQuick.Window 2.2 import com.mycompany.qmlcomponents 1.0 Window { ...... AppModel { ...... } ...... }
实现
setList
和setDimensionalList
两个函数用于接收 QML 传递过来的数组,并通过Q_INVOKABLE
宏将setList
和setDimensionalList
这两个函数暴露给 QML。// 头文件 class AppModel : public QObject { Q_OBJECT public: explicit AppModel(QObject *parent = 0); Q_INVOKABLE void setList(const QList<int>& l); Q_INVOKABLE void setDimensionalList(const QVariantList& l); ...... };
// cpp文件
void AppModel::setList(const QList<int> &l)
{
foreach (int i, l) {
qDebug() << i;
}
}
void AppModel::setDimensionalList(const QVariantList &l)
{
foreach (QVariant i, l) {
QList <QVariant> p = i.toList();
qDebug() << p[0].toInt() << p[1].toInt() << p[2].toInt();
}
}
最后在 QML 中定义 JavaScript 数组,并分别调用
setList
和setDimensionalList
将数组传递到 C++ 的AppModel
模型中。property var array: [1, 2, 3, 6, 5, 4] property var dimensionalarray : [[1,2,3], [4,5,6]] AppModel { Component.onCompleted: { setList(array); setDimensionalList(dimensionalarray) } }
程序输出如下:
1
2
3
6
5
4
1 2 3
4 5 6
附:QML中数组的使用方法
function() {
var points = new Array
// 添加一维数组
points.push(1);
// 添加二维数组
points.push([2, 3])
// 获取长度
points.length
}
更多函数参考:http://www.w3school.com.cn/jsref/jsref_obj_array.asp
参考文章:
How to pass a 2 dimensional float array from QML to C++?