当尝试使用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

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();
}

javascript - 将回调作为参数发送给QJSValue::callAsConstructor()-LMLPHP

最佳答案

按照定义,JSON没有任何东西可以表示函数,因此JSON.stringify将一个函数作为属性会导致“缺少”属性(或数组中的函数或函数)。

07-28 01:26