在利用Qt框架的QWebEngineView進(jìn)行嵌入瀏覽器開發(fā)時,可以很方便的通過
QWebChannel實現(xiàn)與js的交互汛骂,本節(jié)內(nèi)容簡單講解js向Qt應(yīng)用程序發(fā)送消息密任,實現(xiàn)對本地程序notepad的調(diào)用吞鸭。
要實現(xiàn)js向Qt應(yīng)用程序發(fā)送消息嫉入,可以分如下幾步:
1. 創(chuàng)建自己的C++交互類:用于接收消息的接口必須定義為public slots:
硫痰,以供js調(diào)用:
jscontext.h
#ifndef JSCONTEXT_H
#define JSCONTEXT_H
#include <QObject>
#include <QWebEnginePage>
class JsContext : public QObject
{
Q_OBJECT
public:
JsContext(QObject *parent = 0);
~JsContext(){}
signals:
void openNotepad(const QString& msg);
public slots:
// 接收前端js發(fā)送來的消息
void onRecvMsg(const QString& msg, const QString para);
};
#endif // JSCONTEXT_H
jscontext.cpp
#include "jscontext.h"
JsContext::JsContext(QObject *parent /*= 0*/) : QObject(parent)
{
}
void JsContext::onRecvMsg(const QString &msg, const QString para)
{
if (msg == "notepad")
{
emit openNotepad(para);
}
}
2. 創(chuàng)建QWebChannel通道,在QWebChannel中注冊C++交互類對象,并設(shè)置為當(dāng)前頁面的通道:
m_pJsContext = new JsContext(this);
m_pWebChannel = new QWebChannel(this);
m_pWebChannel->registerObject("context_qt", m_pJsContext);
m_pWebView->page()->setWebChannel(m_pWebChannel);
接下來看看頁面這邊的實現(xiàn):
首先創(chuàng)建一個測試的html頁面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webchannel TEST</title>
</head>
<body>
<p>webchannel test</p>
<script type="text/javascript" src="./js/qwebchannel.js"></script>
<script type="text/javascript" src="./js/opennotepad.js"></script>
<button type="button" onclick="open_notepad('notepad', 'test.txt')">打開notepad </button>
</body>
</html>
實現(xiàn)我們的js工具包opennotepad.js
var context_qt;
// 初始化
function init_qt()
{
if (typeof qt != 'undefined')
{
new QWebChannel(qt.webChannelTransport, function(channel)
{
context_qt = channel.objects.context_qt; //從通道中獲取交互對象
})
}
else
{
console.log("qt object obtain fail!");
}
}
// 向qt發(fā)送消息
function sendMessage(msg, para)
{
if(typeof context_qt == 'undefined')
{
console.log("context_qt object obtain fail!");
}
else
{
context_qt.onRecvMsg(msg, para); //調(diào)用交互對象接口助赞,接收消息
}
}
// 控件響應(yīng)函數(shù)
function open_notepad(msg, para)
{
sendMessage(msg, para);
}
init_qt();
備注:qwebchannel.js文件可以在qt自帶的例子或網(wǎng)上下載拷貝
運(yùn)行效果: