0

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. it recognises the object, but none of its methods.

mainwindow.cpp code:

#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:

#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 can not call the function of the app class, you help me Thank you

david.yan
  • 1
  • 1

1 Answers1

0

Have you tried using Q_INVOKABLE on a normal (i.e., non slot function)? 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.

Typically that approach works for me. I've never combined Q_SLOT and Q_INVOKABLE, though.

Eli Hooten
  • 994
  • 2
  • 9
  • 23