I stumbled upon this while researching about QT: http://doc.qt.nokia.com/4.7-snapshot...ys-and-objects
JavaScript arrays and objects
There is built-in support for automatic type conversion between QVariantList and JavaScript arrays, and QVariantMap and JavaScript objects.
For example, the function defined in QML below left expects two arguments, an array and an object, and prints their contents using the standard JavaScript syntax for array and object item access. The C++ code below right calls this function, passing a QVariantList and a QVariantMap, which are automatically converted to JavaScript array and object values, respectively:
// MyItem.qml
Item {
function readValues(anArray, anObject) {
for (var i=0; i<anArray.length; i++)
console.log("Array item:", anArray[i])
for (var prop in anObject) {
console.log("Object item:", prop, "=", anObject[prop])
}
}
}
// C++
QDeclarativeView view
(QUrl::fromLocalFile("MyItem.qml"));
QVariantList list;
list << 10 << Qt::green << "bottles";
QVariantMap map;
map.insert("language", "QML");
map.
insert("released",
QDate(2010,
9,
21));
QMetaObject::invokeMethod(view.
rootObject(),
"readValues",
// MyItem.qml
Item {
function readValues(anArray, anObject) {
for (var i=0; i<anArray.length; i++)
console.log("Array item:", anArray[i])
for (var prop in anObject) {
console.log("Object item:", prop, "=", anObject[prop])
}
}
}
// C++
QDeclarativeView view(QUrl::fromLocalFile("MyItem.qml"));
QVariantList list;
list << 10 << Qt::green << "bottles";
QVariantMap map;
map.insert("language", "QML");
map.insert("released", QDate(2010, 9, 21));
QMetaObject::invokeMethod(view.rootObject(), "readValues",
Q_ARG(QVariant, QVariant::fromValue(list)),
Q_ARG(QVariant, QVariant::fromValue(map)));
To copy to clipboard, switch view to plain text mode
I tried to integrate this to my application. Although, instead of using QVariantList, I used a QStringList to retrieve values from my text file.
...
while ( !in.atEnd() )
{
//qDebug() << "message: " << str;
line.append(str);
}
QStringList line;
...
QTextStream in(&inputFile);
while ( !in.atEnd() )
{
QString str = in.readLine();
//qDebug() << "message: " << str;
line.append(str);
}
To copy to clipboard, switch view to plain text mode
Afterwards, I used the QMetaObject thing to pass the QStringList to my javascript function.
QMetaObject::invokeMethod(view.
rootObject(),
"readValues",
//WHERE readValues is my Javascript function
QMetaObject::invokeMethod(view.rootObject(), "readValues",
Q_ARG(QVariant, QVariant::fromValue(line)));
//WHERE readValues is my Javascript function
To copy to clipboard, switch view to plain text mode
It works. And it reads and displays the retrieved values when I use console.log() in my .qml file. HOWEVER, whenever this it executed, I get a TypeError: file:///C:/Users/MYCOMP/Qt/Projectproj-build-desktop/qml/Projectproj/main.qml:65: TypeError: Result of expression 'anArray' [undefined] is not an object.
How come?
Bookmarks