使用QWebView與所載入的HTML頁面進行通訊
阿新 • • 發佈:2019-01-28
#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物件通訊的樣子。