QT-Qweb Callback not working in the example here

我们两清 提交于 2019-12-11 17:56:15

问题


Now this code works with the slot mechanism. However, I want to try out the signal way also. However, I am unable to do so? Any more ideas on it?

I want to call function f1 of the Javascript from the QT. However, I am unable to do so. I don't see the callback being received by the JS f1(). I have followed the earlier post on it, Qt QWEBview JavaScript callback . However, I am unable to do so. Here is my code.

#include <QtGui/QApplication>
#include <QApplication>
#include <QDebug>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>

class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
     QWebView *view;
     MyJavaScriptOperations();

    Q_INVOKABLE qint32 MultOfNumbers(int a, int b) {
        qDebug() << a * b;
        return (a*b);
    }
public slots:
     void callback();
public:

void  firecb();

 signals:
      void done();
};


MyJavaScriptOperations::MyJavaScriptOperations()
{
    view = new QWebView();
    view->resize(400, 500);

    connect(view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(callback()));

    view->load(QUrl("./shreyas.html"));

    view->show();


    qDebug()<<view;


}

void MyJavaScriptOperations::callback()
{
    qDebug()<<"Sending hello text";
    QString function = "f1()";
    view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", this);
    //view->page()->mainFrame()->evaluateJavaScript("f1()");
    done();
}

void  MyJavaScriptOperations::firecb()
{
     qDebug()<<"Emitting Signal";
     done();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);


    MyJavaScriptOperations *jvs = new MyJavaScriptOperations;
    jvs->firecb();

    return a.exec();
}
#include "main.moc"

The html file.

<head>
    <script LANGUAGE="JavaScript">


function f1()
{
   alert('f1 called from qtclass with message');
   document.write("HELLLLLLLLL");
}
myoperations.callback(f1);


function f2()
{
   var result = myoperations.MultOfNumbers(3,7);
   document.write(result);
    alert('f1 called from qtclass with message');
}


function f3()
{

    alert('f3');
}

myoperations.done.connect(f3);
    </script>
</head>
<body>
    test html
<input type="button" value="click" onclick="f2()">
</body>

回答1:


You have to inject your QObject calling addToJavaScriptWindowObject() in a slot invoked by QWebFrame::javaScriptWindowObjectCleared() signal, elsewhere loading an URL will clear all JS objects previously injected. See documentation on addToJavaScriptWindowObject.



来源:https://stackoverflow.com/questions/22037838/qt-qweb-callback-not-working-in-the-example-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!