当您尝试使用 QJSEngine 将对象从 C++ 传递到 JavaScript 时,所有字段都神秘地消失了,其值由函数存储。为什么会这样?
qjsengine-bug
QT += core qml quick quickcontrols2
TARGET = qjsengine-bug
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11 console
SOURCES += main.cpp
主文件
#include <QCoreApplication>
#include <QJSValueIterator>
#include <QJSEngine>
#include <QJSValue>
#include <QtGlobal>
#include <iostream>
void myMessageOutput(
QtMsgType t,
const QMessageLogContext &c,
const QString &msg
) {
Q_UNUSED(t);
Q_UNUSED(c);
std::cout << msg.toStdString() << "\n";
}
int main(int argc, char *argv[]) {
qInstallMessageHandler(myMessageOutput);
QCoreApplication app(argc, argv);
QJSEngine engine;
engine.installExtensions(QJSEngine::ConsoleExtension);
QJSValue constructor = engine.evaluate(
"(function Component(props){console.log(JSON.stringify(props))})"
);
QJSValue callBack = engine.evaluate("(function(text){console.log(text)})");
callBack.call({"There is no error. Valid JavaScript code..."});
callBack.call({"Let's create an object, add a couple of props to it"});
QJSValue object = engine.newObject();
object.setProperty("First", 1);
object.setProperty("Second", callBack);
object.setProperty("Third", "#2");
QJSValueIterator iter(object);
while (iter.hasNext()) {
iter.next();
callBack.call({
QString("name: %1, value: %2")
.arg(iter.name())
.arg(iter.value().toString())
});
}
callBack.call({"Correct. Three fields"});
callBack.call({"Let's try to pass an object to the constructor parameters"});
constructor.callAsConstructor({object});
callBack.call({"Where did the second property go?"});
return app.exec();
}
这里的重点是
JSON.stringify
它不知道如何将函数转换为字符串,所以它只是跳过了带有函数的属性。例子: