这个例子很旧,但仍然有效,而且非常简单和干净。
此外,您可能想看看qtwebkit-bridge和教程。
编辑
添加一个名为myclass.h
#include "html5applicationviewer/html5applicationviewer.h"
class MyClass : public Html5ApplicationViewer
{
Q_OBJECT
public:
explicit MyClass(QWidget *parent=0);
private slots:
void addToJavaScript();
public slots:
QString test(const QString ¶m);
};
添加一个名为myclass.cpp
#include <QDebug>
#include <QGraphicsWebView>
#include <QWebFrame>
#include "myclass.h"
MyClass::MyClass(QWidget *parent) : Html5ApplicationViewer(parent) {
QObject::connect(webView()->page()->mainFrame(),
SIGNAL(javaScriptWindowObjectCleared()), SLOT(addToJavaScript()));
}
void MyClass::addToJavaScript() {
webView()->page()->mainFrame()->addToJavaScriptWindowObject("MyClass", this);
}
QString MyClass::test(const QString ¶m) {
qDebug() << "from javascript " << param;
return QString("from c++");
}
在你的.pro
添加
SOURCES += main.cpp myclass.cpp
HEADERS += myclass.h
在你的.html
添加
try {
alert(MyClass.test("test string"));
} catch(err) {
alert(err);
}
在您的main.cpp
添加中包括:
#include "myclass.h"
并改变:
Html5ApplicationViewer viewer;
至:
MyClass viewer;