【问题标题】:Send callback as argument to QJSValue::callAsConstructor()将回调作为参数发送到 QJSValue::callAsConstructor()
【发布时间】:2019-07-23 19:51:26
【问题描述】:

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

ma​​in.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 c++ qt qml qt5


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      相关资源
      最近更新 更多