1. 程式人生 > >OpenLayers學習筆記(二)— QML與HTML通訊之畫圖

OpenLayers學習筆記(二)— QML與HTML通訊之畫圖

QML與 HTML通訊—實現QML中點選功能按鈕在地圖上畫圖

作者: 狐狸家的魚

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);
       }
}