本文介绍了从Javascript端调用Qt函数(QWebView)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Qt项目,可以加载任何HTML页面到Web视图。我在 main.cpp 文件中有以下代码:

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 <QApplication>
#include <QWebView>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWebView *view = new QWebView();

    view->resize(400, 500);
    view->load(QUrl("file:///absolute/path/to/my/html/file.html"));
    view->show();

    return app.exec();
}

这很好,但我想通过Javascript从C ++端调用一个函数加载在 file.html (加载在 QWebView )。

This works fine, but I want to call a function from C++ side via Javascript loaded in file.html (loaded in QWebView).

因此,具有以下C ++函数:

So, having the following C++ function:

void sumOfNumbers (a, b)
{
   qDebug() << a + b;
}

我想从Javascript端调用:

I want to call it from Javascript side:

someMethod("sumOfNumber", 12, 23);

35

推荐答案

>您需要在继承自QObject的类中定义要调用的方法。

You need to define the methods you want to call in a class that inherits from QObject.

从QWebView中,可以调用 page 以检索其QWebPage。使用QWebPage,您可以调用 mainFrame()来检索其QWebFrame。 QWebFrame有一个 addToJavaScriptWindowObject()方法,可以将QObject绑定到Web上下文中:

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);

然后从JavaScript端我可以调用任何插槽或Q_INVOKABLE方法在我的QObject只是通过引用它上面提供的名称(在这种情况下为somefoo):

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();

更多信息:

更新 - 添加原始示例。

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"

索引.html:

<html>
    <body>
        <script type="text/javascript">
            myoperations.sumOfNumbers(12, 23);
        </script>
    </body>
</html>

这篇关于从Javascript端调用Qt函数(QWebView)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:57