当前位置:网站首页>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
边栏推荐
- Laravel implements the Holy Grail model with template inheritance
- Requirements for SQL server to retrieve SQL and user information
- egg测试的知识大全--mock、superTest、coffee
- Blender programmed terrain production
- If the route reports an error after deployment according to the framework project
- 修仙真实世界与游戏世界
- Vscode settings JSON configuration
- What are the most popular recruitment technical skills in 2022? You can't think of it
- Edit, cancel, pull up menu
- Three 之 three.js (webgl)简单实现根据点绘制线/弧线(基于LineGeometry / Line2 / LineMaterial,绘制两点基于圆心的弧线段)
猜你喜欢
Create cells through JS (while loop)
Blender programmed terrain production
SQL Server检索SQL和用户信息的需求
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
Three of three JS (webgl) is simple to draw lines / arcs according to points (based on linegeometry / line2 / linematerial, draw two arc segments based on the center of the circle)
Basic knowledge of redis
Laravel [view]
open3d材质设置参数分析
What are the most popular recruitment technical skills in 2022? You can't think of it
[the background color changes after clicking a line]
随机推荐
Use of ES6 array
Cross domain CORS relationship~
Domain driven model DDD (III) -- using saga to manage transactions
[untitled] Notepad content writing area
3d slicer中拉直体的生成
Arithmetic and logical operations
If I am PM's performance, movie VR ticket purchase display
Interpretation of common SQL statements
Anti crawler (0): are you still climbing naked with selenium? You're being watched! Crack webdriver anti crawler
Open source rule engine - Ice: dedicated to solving flexible and complex hard coding problems
How to set the initial value of El input number to null
Nécessité de précharger les cookies dans le sélénium
点击添加按钮--出现一个框框(类似于添加学习经历-本科-研究生)
Tslint annotations ignore errors and restful understanding
Differences between auto and decltype inference methods (learning notes)
Uniapp wechat sharing
JS time format conversion
狼叔来找翻译人员了--plato--持续翻译中.....
String class understanding - final is immutable
Use pagoda + Xdebug + vscode to debug code remotely