qml与html通信(QWebChannel的使用)
QML部分
流程:
实现流程:
1、注册QtObject对象,这里要声明WebChannel.id ,html通过这个id进行访问
2、定义WebChannel对象,通过registeredObjects属性添加需要在html中访问的对象
3、WebEngineView对象,设置webChannel属性为自定义对象,建立连接
import QtWebEngine 1.8
import QtWebChannel 1.0
QtObject {
id: qtObject
WebChannel.id: "channelqtObject"
signal signaltest(var test)
function getBodyHeight(bodyHeight)
{
console.log("---bodyHeiht---",bodyHeight);
}
}
//*********************webQues 加载html****************************//
Rectangle{
id: webQuesRect
width: 648
z:1
height: 340
visible: false
anchors.left: headerRect.right
anchors.leftMargin: 20
anchors.top: parent.top
color: "transparent"
WebEngineView {
id:webQues
anchors.fill:parent
backgroundColor: "white"
webChannel: myChannel
smooth: true
property url clearweb: "qrc:/resources/clearweb.html"
}
}
WebChannel {
id: myChannel
registeredObjects: [qtObject]
}
html部分
1、 引入外部qwebchannel.js 文件
2、new QWebChannel(qt.webChannelTransport, function (channel) {
console.log(“—QWebChannel–”)
qtObject = channel.objects.channelOcrQuesSearch;
}
);
创建QWebChannel对象,channel.objects就是你在qml中channel中注册的对象数组,通过id就可以访问到qml的对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body >
<style>
.wrapper {
background-color: #000;
color: #FFF;
font-size: 24px
}
</style>
<script type="text/javascript" src="http://img.jyeoo.net/banyin/pen/qwebchannel.js"></script>
<script type="text/javascript">
var qtObject;
new QWebChannel(qt.webChannelTransport, function (channel) {
console.log("---QWebChannel--")
qtObject = channel.objects.channelqtObject;
}
);
function js_getBodyHeight()
{
qtObject.getBodyHeight(document.body.scrollHeight);
}
</script>
<div class="wrapper">
<div class="qml-stem">
<p style=""><span onclick="go_back(body.offsetHeight)">在做DNA的粗提取与鉴定实验时,玻璃棒搅拌出的较纯净的DNA的颜色以及DNA遇二苯胺(沸水浴)染成的颜色分别是<span
style="font-family: 'Times New Roman'"
qml-space-size="4"> </span>( )</span></p>
</div>
</body>
</html>
##另外
qml中访问html中的函数
WebEngineView中提供runJavaScript方法,可以直接运行html中的javaScript函数
webQues.runJavaScript("js_getBodyHeight()",null);
本文当学习记录使用,如果有不对的地方欢迎各位赐教,共同探讨学习