作者: 狐狸家的鱼
Github: 八至
一、HTML-map
var drarGraphic;
var drawType;function addDrawInteraction(){
var geometryFunction;
console.log(drawType);
if(drawType !== ''){
if (drawType === 'RecTangle') {
drawType = 'Circle';
geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
}
drarGraphic = new ol.interaction.Draw({
type:drawType,
source:vectorSource,//数据源
geometryFunction: geometryFunction
});
map.addInteraction(drarGraphic);//添加画图功能在地图中
}
};
二、QML
1.创建WebChannel
WebControl.qml,此qml页面为创建webchannel
import QtQuick 2.7
import QtWebChannel 1.0
QtObject {
//一个具有属性、信号和方法的对象——就像任何普通的Qt对象一样
id: mapController
WebChannel.id: "content"//ID将作为在WebEngineView端的已知对象
//信号
signal drawGraphic(string type) //画图
}
2.将ID分配给WebEngineView,并在该通道注册QtObject的ID。
main.qml
import QtQuick 2.9
import QtQuick.Window 2.3
import QtWebEngine 1.3
import QtWebChannel 1.0
WebControl {//WebControl.qml作为组件
id: map;
}
WebEngineView {
id: mapView_1;
anchors.fill: parent;
url: "./Map.html";//html的url地址
webChannel: WebChannel {
registeredObjects: [map];//注册ID
}
}
3.QML与HTML交互
(1)在HTML端引入WebChannel的JavaScript库
<script type="text/javascript" src="qwebchannel.js"></script>
(2)在windows.onload()事件上创建QWebChannel,并获取后端对象
window.onload =() =>{
new QWebChannel(qt.webChannelTransport, (channel)=> {
var content = channel.objects.content;//自定义
}
(3)html调用QWebChannel的方法,连接到它的信号并访问它的属性
window.onload =() =>{
new QWebChannel(qt.webChannelTransport, (channel)=> {
var content = channel.objects.content;//自定义
//画图
content.drawGraphic.connect((type)=>{//连接WebControl.qml中的drawGraphic(string type)信号
drawType = type;
map.removeInteraction(drarGraphic);
addDrawInteraction();
}); }
(4)qml中画图按钮调用信号
//画线段 这里只贴了画直线的代码 其他画图按钮调用信号方法一样的
BorderButton{
width: right.width/9;
height: btnHeight;
borderbtnText:"Line";
onClicked: {
var type = 'LineString';
console.log('clicked drawLine');
map.drawGraphic(type);
}
}