使用QWebView与所加载的HTML页面进行通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/r5014/article/details/79271483
#include <QWebView>

class CWebInterface: public QWebView
{
    Q_OBJECT
public:
    CWebInterface(QWidget* p=NULL);

signals:
    void pushData(const QString& data);

private slots:
    void onOBJCleared();

public:
    Q_INVOKABLE void showMessage(QString msg);
    Q_INVOKABLE void emitSig();
};

Q_INVOKABLE 标签的函数是可以给JS调用的。pushData信号也可以被js捕捉到。

接下来这样实现:

#include "CWebInterface.h"
#include <QMessageBox>
#include <QWebFrame>

CWebInterface::CWebInterface(QWidget *p)
{
    //恰当的时机把操作对象放入网页
    connect(this->page()->mainFrame(), &QWebFrame::javaScriptWindowObjectCleared,
            this, &CWebInterface::onOBJCleared);

    this->load(QUrl("file:///D:/QtProject/CWidgetWar3Game/index.html"));
}

void CWebInterface::onOBJCleared()
{
    QWebFrame* pFrame = this->page()->mainFrame();
    pFrame->addToJavaScriptWindowObject("operator", this);
}

void CWebInterface::showMessage(QString msg)
{
    QMessageBox::information(0,"msg dialog",msg);
}

void CWebInterface::emitSig()
{
    emit pushData("test data");
}


然后在测试HTML写入测试所用的代码:

<head>
	<mata charset='utf8' />
</head>

<H1>Web Bridge Test Page!</H1>

<script>

function slot_fuc(d)
{
	alert("js slot get data:'" + d + "'")
}

//connect signals
operator.pushData.connect(slot_fuc)

//running on loaded.
operator.showMessage("from js: i'm ready!");
	
alert("i'll emit a 'pushData' signal")

operator.emitSig()

</script>




创建运行并显示这个CWebInterface就可以看到HTML页面和Qt对象通信的样子。





猜你喜欢

转载自blog.csdn.net/r5014/article/details/79271483