None of the tutorials available online show how to create a Qt HTML5 application. Ideally, I just need a way to send data (a string will do) between webkit and Qt.

When I create a Qt HTML5 Application It generates

  1. myApp.pro
  2. html5applicationviewer.pri // comments say dont touch this file
  3. html5applicationviewer.h // comments say dont touch this file
  4. html5applicationviewer.cpp // comments say dont touch this file
  5. main.cpp
  6. index.html

So how do I add a function in C++ to communicate with the browser and how do I add a function in the browser to communicate with C++?

有帮助吗?

解决方案

This example is old but still work and is very simple and clean.

Also you may want to take a look to qtwebkit-bridge and the tutorial.

edit

add a file called 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 &param);
};

add a file called 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 &param) {
    qDebug() << "from javascript " << param;
    return QString("from c++");
}

in your .pro add

SOURCES += main.cpp myclass.cpp
HEADERS += myclass.h

in your .html add

try {
    alert(MyClass.test("test string"));
} catch(err) {
    alert(err);
}

in your main.cpp add include:

#include "myclass.h"

and change:

Html5ApplicationViewer viewer;

to:

MyClass viewer;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top