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

#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对象通信的样子。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值