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

后端 未结 1 593
挽巷
挽巷 2021-02-15 14:21

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

1条回答
  •  南方客
    南方客 (楼主)
    2021-02-15 14:57

    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 ¶m);
    };
    

    add a file called myclass.cpp

    #include 
    #include 
    #include 
    
    #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++");
    }
    

    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;
    

    0 讨论(0)
提交回复
热议问题