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