简体   繁体   English

QtWebkit javascript桥,无法访问Qt对象方法

[英]QtWebkit javascript bridge,Cannot access Qt object methods

Using QtWebkit's javascript bridge, I have created a class to interface the data in my web frame with the rest of my Qt code. 使用QtWebkit的javascript桥,我创建了一个类,用于将Web框架中的数据与其余Qt代码接口。 it recognises the object, but none of its methods. 它可以识别对象,但不能识别其方法。

mainwindow.cpp code: mainwindow.cpp代码:

#include "app.h"
MainWindow::MainWindow(QWidget *parent) :  QWebView(parent)
{
    happ = new app(this);
     m_network = new QNetworkAccessManager(this);
     page()->setNetworkAccessManager(m_network);



     QFile file("E://qt//test.happ//index.html");
     file.open(QIODevice::ReadOnly | QIODevice::Text);
     QTextStream in(&file);
     QString htmlContent = in.readAll();


     addJSObject();
     QObject::connect(page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(addJSObject()));

     setHtml(htmlContent);
 }

void MainWindow::addJSObject()
{
    page()->mainFrame()->addToJavaScriptWindowObject(QString("happ"), happ);
};

app.h code: app.h代码:

#include <QObject>


class app:public QObject
{
public:
    app(QObject *parent);
public slots:
        void os_foo();

signals:
        void win_bar();

};

javascript: javascript:

function a(){
    if(window.happ){ 
        alert("obj: " + typeof happ);            //shows "obj: object" 
        alert("os_foo: " + typeof happ.os_foo); //shows "os_foo: undefined" 
    } 

}

javascript can not call the function of the app class, you help me Thank you javascript无法调用app类的功能,对你有帮助我谢谢

Have you tried using Q_INVOKABLE on a normal (ie, non slot function)? 您是否尝试在常规(即非插槽功能)上使用Q_INVOKABLE Try this 尝试这个

class app:public QObject
{ 
  public:
    app(QObject *parent);
  //public slots:
    Q_INVOKABLE void os_foo();

   signals:
    void win_bar();
};

and then call the function as you are from your JavaScript coode. 然后从JavaScript代码库中直接调用该函数。

Typically that approach works for me. 通常,这种方法对我有用。 I've never combined Q_SLOT and Q_INVOKABLE , though. 我从来没有结合Q_SLOTQ_INVOKABLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM