OpenLayers学习笔记(二)— QML与HTML通信之画图

作者: 狐狸家的鱼

Github: 八至

本文链接:QML与 HTML通信—实现QML中点击功能按钮在地图上画图

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

 

转载于:https://www.cnblogs.com/suRimn/p/10069047.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值