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

时间:2017-08-10 18:32:38

标签: qt qtwebengine

我使用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,但它没有我的类的属性和方法。

QT QWebEnginePage::setWebChannel() transport object

Undefined properties and return types when using QWebChannel

0 个答案:

没有答案