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

时间:2012-06-12 16:48:32

标签: javascript c++ qtwebkit

使用QtWebkit的javascript桥接器,我创建了一个类来将我的Web框架中的数据与我的其他Qt代码进行交互。它识别对象,但没有识别它的方法。

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代码:

#include <QObject>


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

signals:
        void win_bar();

};

的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无法调用app类的功能,你帮帮我谢谢

1 个答案:

答案 0 :(得分:0)

您是否尝试在正常(即非插槽功能)上使用Q_INVOKABLE?试试这个

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

   signals:
    void win_bar();
};

然后从JavaScript coode中调用该函数。

通常这种方法适合我。不过,我从未合并Q_SLOTQ_INVOKABLE