qt傳值給js及js傳值給qt(qt及js的互動)
阿新 • • 發佈:2021-01-06
做js和qt的互動,需要將qwebchannel.js拷貝到當前文件目錄下。
首先看html檔案
.html
<html>
<head>
<script
src="qwebchannel.js">
</script>
<script>
new QWebChannel(qt.webChannelTransport,
function(channel){
window.bridge = channel.objects.webobj; // 註冊 //這裡的webobj需要和qt中webobj保持一致
}
);
function receiverQt()
{
alert("good");
window.bridge.getCoordinates();
}
</script>
<script type="text/javascript">
</script>
</head>
<body>
< div id="googleMap" style="width:1920px;height:1080px;"></div>
</body>
</html>
.h檔案
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtWebEngine>
#include <QWebEngineProfile>
#include <QWebEngineView>
#include <QWebChannel>
#include <QJSEngine>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
public slots:
void onLoadFinished();
void getCoordinates();
private:
QWebEngineView *m_pWebEngineView = nullptr;
QWebChannel *m_pWebChannel = nullptr;
};
#endif // WIDGET_H
.cpp
#include "widget.h"
#include "qgridlayout.h"
#include <qdebug.h>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_pWebEngineView = new QWebEngineView(this);
m_pWebChannel = new QWebChannel(this);
m_pWebChannel->registerObject(QString("webobj"), this); // QWebChannel對Widget類,註冊一個webobj的通訊介質 / webobj需要和js內的保持一致
m_pWebEngineView->page()->setWebChannel(m_pWebChannel);
m_pWebEngineView->setUrl(QUrl("file:///D:/QTProject/GoogleMapOnline/map.html"));
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(m_pWebEngineView);
mainLayout->setMargin(0);
mainLayout->setSpacing(0);
this->setLayout(mainLayout);
connect(m_pWebEngineView, &QWebEngineView::loadFinished, this, &Widget::onLoadFinished);
}
Widget::~Widget()
{
delete m_pWebChannel;
}
void Widget::getCoordinates()
{
qDebug() << "33334445555::::::::"; //這個是接受js傳過來的值
}
void Widget::onLoadFinished()
{
QString strVal = QString("OnMsgFromQt%1").arg("1235455");
m_pWebEngineView->page()->runJavaScript("receiverQt()"); //這個是呼叫js中的function
}
ヾ( ̄▽ ̄)ByeBye