QT QWebchannel 无法访问 CPP 对象方法或属性

QT QWebchannel not able to access CPP object methods or properties

我正在使用 QT 5.9 WebEngine 框架来显示网页。我在页面加载时将 javascript 注入页面,并希望 javascript 能够访问 QT 对象。

我在 JS 中调用了 QWebchannel 回调,但对象方法和属性未定义。

注意:我需要注入所有 JS 代码并且不能更改加载页面的 html 代码。这意味着我不能包含任何 js 脚本,也不能直接在 html 页面中编写任何 js 代码。

这是我的代码:

我使用配置文件创建 QWebEnginePage 对象并注入 JS 文件,如下所示:

// file: webview.cpp, webview extends **QWebEngineView**

QWebEngineScript script;
script.setSourceCode(qwebchannelsource); // source is qwebchannel.js
script.setInjectionPoint(QWebEngineScript::DocumentCreation);
profile->scripts()->insert(script);
QWebEnginePage page* = new QWebEnginePage(profile, this);

QWebChannel *channel = new QWebChannel(page);
page->setWebChannel(channel);
channel->registerObject(QStringLiteral("jshelper"), &JSHelper::instance());

JSHelper

class JSHelper : public QObject
{
public:
    static JSHelper &instance();
    QString someString;
    int someInt;

    Q_INVOKABLE int getInt();
    Q_PROPERTY(int myIntInCppSide READ getInt)

private:
    JSHelper();
};

JS代码

// also injected into the page (like qwebchannel.js) at QWebEngineScript::DocumentReady

new QWebChannel(qt.webChannelTransport, function (channel) {
    var jshelper = channel.objects.jshelper;
    console.warn('qwebchannel triggered');

    // do what you gotta do
    if (jshelper === undefined) {
        console.warn("jshelper is undefined");
    }
    else {
        console.warn("jshelper is awesome");
    }

    console.warn("jshelper value of string " + jshelper.somestring);
    console.warn("jshelper value of int " + jshelper.myIntInCppSide);
    jshelper.myIntInCppSide(function (n) {
        console.warn("jshelper value of int " + n);
    });
});

我的输出:

qwebchannel triggered"
jshelper is awesome"
jshelper value of string undefined"
jshelper value of int undefined"
Uncaught TypeError: jshelper.myIntInCppSide is not a function"

如您所见,我尝试了几个答案中的各种建议,但似乎没有任何方法可以解决我的函数不存在的问题。 即使在使用远程调试时,我也可以看到 jshelper 是 QObject 类型,但它没有我的 class.

的属性和方法

JSHelper class 缺少 Q_OBJECT 宏。正如 official documentation 所说,

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

此外,class 的构造函数也需要 public 以便 Qt 的内省工具能够与 class.

一起工作