Calling a Qt function from the Javascript side (QWebView)

前端 未结 2 1916
借酒劲吻你
借酒劲吻你 2020-12-30 04:32

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          


        
相关标签:
2条回答
  • 2020-12-30 05:06

    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>
    
    0 讨论(0)
  • 2020-12-30 05:23

    Current accepted answer is outdated because Qt moved to WebEngine.

    For WebEngineView the solution for calling Qt from JS is using Qt WebChannel API

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