作者: 狐狸家的魚
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); } }