Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt QWEBview JavaScript callback

How to pass a function "pointer" from JavaScript to a slot?

in JavaScript:

function f1()
{
    alert("f1");
}
qtclass.submit(f1);

and in Qt:

public slots:
    void submit(void * ptr) 
    {
        (void)ptr;
    }

I need the "f1", function to get fired in the JavaScript from the c++, once some processing is done. Also I do not know in advance the name of the function pointer.

like image 674
user457015 Avatar asked Feb 12 '11 01:02

user457015


2 Answers

you should be able to execute your script using QWebFrame::evaluateJavaScript method. See if an example below would work for you:

initializing webview:

QWebView *view = new QWebView(this->centralWidget());
view->load(QUrl("file:///home//test.html"));
connect(view, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));

loadFinished signal handler:

void MyTestWindow::loadFinished(bool)
{
    QVariant f1result = ((QWebView*)sender())->page()->mainFrame()->evaluateJavaScript("f1('test param')");
    qDebug() << f1result.toString();
}

test.html:

<head>
    <script LANGUAGE="JavaScript">
        function f1 (s) 
        {
            alert (s) 
            return "f1 result"
        }
    </script>
</head>
<body>
    test html
</body>

evaluateJavaScript should trigger an alert message box and return QVariant with f1 function result.

hope this helps, regards

like image 121
serge_gubenko Avatar answered Oct 10 '22 04:10

serge_gubenko


You could solve this in another way, by using Qt signals, as follows:

class qtclass
{
   signals:
      void done(QString message);
};

In your HTML file you can connect to this signal, like this:

qtclass.done.connect(f1);

function f1(message)
{
   alert('f1 called from qtclass with message' + message);
}

Then you C++ class does not need to know about the javascript function.

like image 34
Kurt Pattyn Avatar answered Oct 10 '22 04:10

Kurt Pattyn