当前位置:网站首页>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
边栏推荐
- Devops life cycle, all you want to know is here!
- Write the declaration of a function to return the reference of the array, and the array contains 10 string objects (notes)
- Modèle axé sur le domaine DDD (III) - gestion des transactions à l'aide de Saga
- STD:: String implements split
- Why can't V-IF and V-for be used together
- selenium预先加载cookie的必要性
- Requirements for SQL server to retrieve SQL and user information
- 使用宝塔+xdebug+vscode远程调试代码
- After NPM was upgraded, there was a lot of panic
- Double click The jar package cannot run the solution
猜你喜欢

弘玑微课堂 | Cyclone RPA之“灵活的数字员工”执行器
Redis的基本知识

Excel 2016 打开文件第一次打不开,有时空白,有时很慢要打开第二次才行

Three 之 three.js (webgl)简单实现根据点绘制线/弧线(基于LineGeometry / Line2 / LineMaterial,绘制两点基于圆心的弧线段)
![[the background color changes after clicking a line]](/img/3a/709d47fd3a370d86569fb9b560b403.png)
[the background color changes after clicking a line]

Project manager's thinking mode worth trying: project success equation

Cloud computing and cloud native architecture design of openshift

varnish入门

selenium预先加载cookie的必要性
Basic knowledge of redis
随机推荐
Phlli in a VM node
App Store年交易额100万美元只缴15%佣金,中小开发者心里很矛盾
Membarrier (personal learning and understanding)
C test calls the paddlesharp module to recognize pictures and words
d. TS --- for more detailed knowledge, please refer to the introduction on the official website (chapter of declaration document)
What are the most popular recruitment technical skills in 2022? You can't think of it
The prefix of static of egg can be modified, including boots
When is it appropriate for automated testing? (bottom)
Devops life cycle, all you want to know is here!
Processus d'exécution du programme exécutable
2021-11-01
创建进程内存管理copy_mm - 进程与线程(九)
[no title] Click the classification jump page to display the details
Multiple mainstream SQL queries only take the latest one of the data
Laravel routing job
Parsing of string class intern() method
C# ,类库
JVM memory and memory overflow exceptions (personal summary)
2021-10-25
Knowledge of egg testing -- mock, Supertest, coffee