QGIS环境搭建好后,我跟着写了一个基础的项目:使用qgis画布加载矢量数据
首先准备好一个.shp文件,也就是我们的矢量图。
创建一个基类为QMainWindow的项目,在.pro文件里增添xml模块,并引入库文件的目录(自定义)
QT += core gui xml
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
DEFINES += QT_DEPRECATED_WARNINGS
DEFINES += _USE_MATH_DEFINES
LIBS += -L"D:\OSGeo4w\apps\qgis-ltr\lib" -lqgis_core -lqgis_gui -lqgis_3d -lqgis_analysis -lqgis_app -lqgis_native -lqgis_server
LIBS += -L"D:\OSGeo4w\apps\Qt5\lib" -lQt53DCore -lQt53DRender -lQt5Core -lQt5Gui
INCLUDEPATH += "D:\OSGeo4w\apps\qgis-ltr\include"
INCLUDEPATH += "D:\OSGeo4w\include"
INCLUDEPATH += "D:\OSGeo4w\apps\Qt5\include\Qt3DCore"
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
接着我们在main文件中做如下修改:
#include "mainwindow.h"
#include <QApplication>
#include<qgsapplication.h>
#include<qgsproviderregistry.h>
#include<QDebug>
int main(int argc, char *argv[])
{
//QgsApplication有5个参数,前三个需要初始化,第三个参数表示是否激活图像GUI界面false是命令行
QgsApplication app(argc,argv,true);
//设置数据驱动插件目录 单例instance
QgsProviderRegistry::instance("D:/OSGeo4w/apps/qgis-ltr/plugins");
//检查导入的插件列表
qDebug()<<"QGIS data providers loaded"<<QgsProviderRegistry::instance()->providerList()<<endl;
//具体加载数据在MainWindow的成员函数loadShapeFile内
MainWindow w;
w.loadShapeFile();
return app.exec();
}
在MainWindow的头文件里,声明其画布属性,以及加载数据的函数
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<qgsmapcanvas.h>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
//加载矢量数据
void loadShapeFile();
private:
//画布元素
QgsMapCanvas canvas;
};
#endif // MAINWINDOW_H
借来下就是.cpp文件里对函数的具体实现:
#include "mainwindow.h"
#include<qgsvectorlayer.h>
#include<qdebug.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
}
MainWindow::~MainWindow()
{
}
void MainWindow::loadShapeFile(){
//实例化矢量图层 通过准备好的矢量文件绝对路径来初始化
QgsVectorLayer* pVectorLayer = new QgsVectorLayer("D:/qtWorkspace/Shp/china-latest-free/gis_osm_places_a_free_1.shp","地区");
//检查一下是否成功
qDebug()<<"Is layer valid:"<<pVectorLayer->isValid();
//将该图层放入画布里
canvas.setLayers(QList<QgsMapLayer*>()<<pVectorLayer);
//画布也是QWidget的子类,可以设置标题
canvas.setWindowTitle("QGIS二次开发:画布");
canvas.show();
//设置画布大小,来达到可见图层的完整范围
canvas.zoomToFullExtent();
}