Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Qt function from the Javascript side (QWebView)

Tags:

c++

javascript

qt

I have a Qt project that can load any HTML page into a web view. I have the following code in main.cpp file:

#include "mainwindow.h"
#include <QApplication>
#include <QWebView>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWebView *view = new QWebView();

    view->resize(400, 500);
    view->load(QUrl("file:///absolute/path/to/my/html/file.html"));
    view->show();

    return app.exec();
}

This works fine, but I want to call a function from C++ side via Javascript loaded in file.html (loaded in QWebView).

So, having the following C++ function:

void sumOfNumbers (a, b)
{
   qDebug() << a + b;
}

I want to call it from Javascript side:

someMethod("sumOfNumber", 12, 23);

that will print in the console 35 (12 + 23).

How can I do this?

like image 584
Ionică Bizău Avatar asked Oct 19 '13 18:10

Ionică Bizău


1 Answers

You need to define the methods you want to call in a class that inherits from QObject.

From a QWebView, you can call page() to retrieve its QWebPage. With a QWebPage, you can call mainFrame() to retrieve its QWebFrame. QWebFrame has a addToJavaScriptWindowObject() method which lets you bind QObject's into the web context:

class MyObject {
public slots:
    void doSomething();
};

MyObject *foo = new MyObject;
myWebView->page()->mainFrame()->addJavaScriptToWindowObject("somefoo", foo);

Then from the javascript side I can call any slot or Q_INVOKABLE method on my QObject simply by referencing it by the name provided above ("somefoo" in this case):

somefoo.doSomething();

More info here: http://qt-project.org/doc/qt-5.1/qtwebkit/qwebframe.html#addToJavaScriptWindowObject

Update - adding the original example.

main.cpp:

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

class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    Q_INVOKABLE void sumOfNumbers(int a, int b) {
        qDebug() << a + b;
    }
};

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

    QWebView *view = new QWebView();
    view->resize(400, 500);
    view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", new MyJavaScriptOperations);
    view->load(QUrl("file:///path/to/my/index.html"));
    view->show();

    return a.exec();
}

#include "main.moc"

index.html:

<html>
    <body>
        <script type="text/javascript">
            myoperations.sumOfNumbers(12, 23);
        </script>
    </body>
</html>
like image 76
ksimons Avatar answered Sep 28 '22 07:09

ksimons