简体   繁体   中英

Calling a Qt function from the Javascript side (QWebView)

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?

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>

Current accepted answer is outdated because Qt moved to WebEngine .

For WebEngineView the solution for calling Qt from JS is using Qt WebChannel API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM