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