Qgis 基于Qt环境下的开发:第三节《添加要素-线》
接下来我们来添加线要素,其实画点画线的方法有好多种,这里我就介绍一种,不多说了,我们来看代码:
``#include "mainwindow.h"
include "ui_mainwindow.h"
include <qgsmapcanvas.h>
include <qgsvectorlayer.h>
include
include <qgssymbol.h>
include <qgssymbollayer.h>
include <qgsvectordataprovider.h>
- MainWindow::MainWindow(QWidget *parent)
- QMainWindow(parent)
{
//老规矩我们来创建画布
QgsMapCanvas *canvas = new QgsMapCanvas(this);
//添加一个背景矢量图层
QString path = "D:/Qt/bbb.shp";
QgsVectorLayer *layer = new QgsVectorLayer(path,"MyPoint","ogr");
//在这里缺少一步<创建链表>,我把QList<QgsMapLayer *>Layers设置成全局变量
//这个是线要素的添加方法,我们跳进函数来看一下
AddLine();
//将矢量层追加到链表中
Layers.append(layer);
//设置画布缩放
canvas->setLayers(layers);
canvas->zoomToFullExtent();
//设置画布背景颜色,当然这个可以根据你自己的需求来设定
canvas->setCanvasColor(QColor(124,134,205));
//设置画布为当前中心窗口
this->setCentralWidget(canvas);
}
MainWindow::~MainWindow()
{
}void MainWindow::AddLine()
{
// 创建一个线图层。
QgsVectorLayer *Line_Layer = new QgsVectorLayer("LineString?crs=epsg:4326","MyLine","memory");
QgsVectorDataProvider *dataProder =Line_Layer->dataProvider();
//在指定坐标添加点
QgsFeature feature;
QgsGeometry geometry = QgsGeometry::fromPointXY(QgsPointXY(50,50));
//通过点坐标进行画线
QgsPolyline line ;
line << QgsPoint(100.4443,32.2123) << QgsPoint(130.5557,50.4445);
geometry =QgsGeometry::fromPolyline(line);
feature.setGeometry( geometry );
dataProder->addFeatures(QgsFeatureList()<< feature);
Line_Layer->updateExtents();
//将线图层加载到链表中
layers.append(Line_Layer);
}``
实现如下图:
如果有什么问题,大家可以来探讨,本人QQ895996365