当前位置:网站首页>Use of qwbengneview and qwebchannel.
Use of qwbengneview and qwebchannel.
2022-04-23 05:28:00 【Oriental forgetfulness】
Want to be in qt Load web pages into widget in , Need to be used QWbEngneView, If you want to communicate with the web side, you can use QWebChanel. You can use it, of course QWebSocket.
QWbEngneView How to use it is as follows :
m_pWebView = new QWebEngineView(this);
QString htmlPath = QApplication::applicationDirPath()+"/test.html";
QFile file(htmlPath);
if (!file.exists())
return;
` m_pWebView->load(QUrl("file:///" + htmlPath));
Use QWebChanel The method is as follows :
m_pWebChannel = new QWebChannel(this);
m_pWebChannel->registerObject(QString("qtui"), this);//qtui This logo can be defined at will , as long as web In the middle html Is also used qtui You can communicate .
m_pWebView->page()->setWebChannel(m_pWebChannel);
QWebChanel and web The method of communication is as follows :
1、 to signal to ,web Responsible for the connection .
2、 Create slot functions , Give Way web Call this slot yourself .
3、 call runJavaScript() This interface , Call directly web Just define the function , And it supports synchronous and asynchronous sending .
4、 Create object properties from header file , Give Way web The client directly uses this object , We can get from this object web Given value . as follows :m_content.


Code example 1 as follows :
The header file
#ifndef WEBTEST_H
#define WEBTEST_H
#include <QtWidgets>
#include <QWebEngineView>
#include <QWebChannel>
class WebTest : public QWidget
{
Q_OBJECT
public:
WebTest(QWidget *parent = nullptr);
private:
void initUi();
void initConncetion();
// load html file
void loadHtml();
// obtain js Function return value
QString getJsRetString();
public slots:
void recieveJsMessage(const QString& jsMsg);
private:
QWebEngineView *m_pWebView;
QWebChannel* m_pWebChannel;
QPushButton* m_callJSBtn;
QPushButton* m_getJsRetBtn;
QLabel* m_lab;
};
#endif // WEBTEST_H
cpp file
#include "webtest.h"
#include <QFile>
#include <QCoreApplication>
WebTest::WebTest(QWidget *parent) : QWidget(parent)
{
initUi();
initConncetion();
}
void WebTest::initUi()
{
m_callJSBtn = new QPushButton(QStringLiteral(" call JS"),this);
m_getJsRetBtn = new QPushButton(QStringLiteral(" obtain JS Return value "),this);
m_lab = new QLabel(this);
m_pWebView = new QWebEngineView(this);
m_pWebChannel = new QWebChannel(this);
QGridLayout* lay = new QGridLayout();
lay->addWidget(m_pWebView,0,0,5,5);
lay->addWidget(m_callJSBtn,0,5,1,1);
lay->addWidget(m_getJsRetBtn,1,5,1,1);
lay->addWidget(m_lab,2,5,1,1);
this->setLayout(lay);
m_callJSBtn->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
m_getJsRetBtn->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
m_lab->setStyleSheet("background:rgba(0,0,155,100)");
loadHtml();
m_pWebChannel->registerObject(QString("qtui"), this);
m_pWebView->page()->setWebChannel(m_pWebChannel);
}
void WebTest::initConncetion()
{
// call JS
connect(m_callJSBtn, &QPushButton::clicked, [&]()
{
QString jsStr = QString("addCircle()");
m_pWebView->page()->runJavaScript(jsStr);// Asynchronous call
});
// obtain JS Return value
connect(m_getJsRetBtn, &QPushButton::clicked, [&]()
{
auto str = getJsRetString();
m_lab->setText(str);
});
}
// Loading the map
void WebTest::loadHtml()
{
QString htmlPath = QCoreApplication::applicationDirPath() + "/BMap.html";
QFile file(htmlPath);
if (!file.exists())
{
return;
}
m_pWebView->load(QUrl("file:///" + htmlPath));
}
// obtain web End return value
QString WebTest::getJsRetString()
{
QEventLoop loop;
QString jsStr = "getInfo();";
QString retStr{};
// Synchronized through loop The loop waits until the callback data comes up and then continues
m_pWebView->page()->runJavaScript(jsStr, [&](const QVariant &v)
{
retStr = v.toString();
loop.quit();
});
loop.exec();
return retStr;
}
// Receive from webhtml The news of
void WebTest::recieveJsMessage(const QString& jsMsg)
{
m_lab->setText(jsMsg);
}
html file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:" Microsoft YaHei ";}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=AEdSNAu4uSOTMaQgiuFizrkNwheoSVHF"></script>
<script src="./qwebchannel.js"></script>
<title>Web test </title>
</head>
<body>
<div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
// Baidu Maps API function
var map = new BMap.Map("allmap"); // establish Map example
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // Initialize map , Set the coordinates of the center point and the zoom level of the map
// Add a map type control
map.addControl(new BMap.MapTypeControl({
mapTypes:[
BMAP_NORMAL_MAP,
BMAP_HYBRID_MAP
]}));
map.setCurrentCity(" Beijing "); // Set up a map showing the city This item must be set
map.enableScrollWheelZoom(true); // Turn on mouse wheel zoom
// Add a circular cover
function addCircle()
{
var point = new BMap.Point(116.404, 39.915);
var circle = new BMap.Circle(point, 6000, { strokeColor: "red", strokeWeight: 5, strokeOpacity: 0.3 }); // Create circles
map.addOverlay(circle); // Add circle
// Here it is circle Add a click event
circle.addEventListener("click", function (event)
{
new QWebChannel(qt.webChannelTransport, function (channel) {
var qtui = channel.objects.qtui;
qtui.recieveJsMessage(" What do you want me to do !");
})
});
}
// Get string text
function getInfo()
{
var textString = "HTML js Return value ";
return textString;
}
</script>
Code example 2 as follows :
The header file
#ifndef TESTINTERFACE_H
#define TESTINTERFACE_H
#include <QObject>
#include <QMessageBox>
class testinterface : public QObject
{
Q_OBJECT
Q_PROPERTY(QString content MEMBER m_content)
public:
testinterface();
void send(int type,QString msg);
signals:
void dataChanged(QString content);
void sendData(QString content);
public slots:
void jscallme(QString msg);
private:
QString m_content;
};
#endif // TESTINTERFACE_H
cpp file
#include "testinterface.h"
testinterface::testinterface()
{
}
void testinterface::send(int type, QString msg)
{
if (type == 0)
{
emit dataChanged(msg);
}
else if (type == 1)
{
emit sendData((msg));
}
}
void testinterface::jscallme(QString msg)
{
QMessageBox::information(NULL, "title", QString(QStringLiteral(" Test transmission parameters :%1\n Test variable :%2")).arg(msg).arg(m_content));
}
html file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="qwebchannel.js"></script>
<script type="text/javascript">
var recvData=function(text)
{
document.write(" test 2:"+text+"</br>");
}
var updateattribute=function(text)
{
document.write(" test 1:"+text+"</br>");
}
new QWebChannel(qt.webChannelTransport,
function(channel){
var testinterface = channel.objects.testinterface;
window.foo = testinterface;
testinterface.content=" May you be happy and prosperous ";
testinterface.jscallme(" Happy New Year! ");
testinterface.dataChanged.connect(updateattribute);
testinterface.sendData.connect(recvData);
});
</script>
</body>
</html>
版权声明
本文为[Oriental forgetfulness]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220543306930.html
边栏推荐
- [triangle Yang Hui triangle printing odd even cycle JS for break cycle]
- 3d slicer中拉直体的生成
- Laravel database
- JVM memory and memory overflow exceptions (personal summary)
- Laravel implements the Holy Grail model with template inheritance
- Basic knowledge of redis
- [untitled] Notepad content writing area
- 史上最强egg框架的error处理机制
- Excel 2016 cannot open the file for the first time. Sometimes it is blank and sometimes it is very slow. You have to open it for the second time
- Error handling mechanism of the strongest egg framework in history
猜你喜欢

領域驅動模型DDD(三)——使用Saga管理事務

如果我是pm之 演出电影vr购票展示

open3d材质设置参数分析

2021-10-12

How to add beautiful code blocks in word | a very complete method to sort out and compare

Open source rule engine - Ice: dedicated to solving flexible and complex hard coding problems

Three 之 three.js (webgl)旋转属性函数的简单整理,以及基于此实现绕轴旋转的简单案例

创建进程内存管理copy_mm - 进程与线程(九)

selenium預先加載cookie的必要性

Modèle axé sur le domaine DDD (III) - gestion des transactions à l'aide de Saga
随机推荐
If I am PM's performance, movie VR ticket purchase display
Self incrementing sequence creation of MySQL
2021-11-01
Necessity of selenium preloading cookies
selenium預先加載cookie的必要性
Watch depth monitoring mode
egg中的多进程模型--egg文档搬运工
Redis的基本知识
Domain driven model DDD (III) -- using saga to manage transactions
如果我是pm之 演出电影vr购票展示
[triangle Yang Hui triangle printing odd even cycle JS for break cycle]
SQL Server检索SQL和用户信息的需求
JS time format conversion
The prefix of static of egg can be modified, including boots
Getting started with varnish
phphphphphphphp
Fast application fuzzy search
Uniapp wechat sharing
4 most common automated test challenges and Countermeasures
Excel 2016 cannot open the file for the first time. Sometimes it is blank and sometimes it is very slow. You have to open it for the second time