How to send data to and from the browser with a Qt HTML5 Application

有些话、适合烂在心里 提交于 2019-12-04 11:00:42

问题


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


回答1:


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;


来源:https://stackoverflow.com/questions/18475794/how-to-send-data-to-and-from-the-browser-with-a-qt-html5-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!