PyQgis Cookbook - 简单独立应用示例

1. PyCharm环境下配置PyQgis

  1. 安装QGIS软件;
  2. 在Pycharm Project中配置Python,如下:
    在这里插入图片描述

2. Qgis独立脚本的初始化

from qgis.core import *

# Supply path to qgis install location
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)

# Create a reference to the QgsApplication.  Setting the
# second argument to False disables the GUI.
qgs = QgsApplication([], False)

# Load providers
qgs.initQgis()

# Write your code here to load some layers, use processing
# algorithms, etc.

# Finally, exitQgis() is called to remove the
# provider and layer registries from memory
qgs.exitQgis()
  • 1)首先,我们导入 qgis.core 模块并配置前缀路径。前缀路径是 QGIS 在系统上安装的位置,True 表示使用默认路径:

setPrefixPath(“/path/to/qgis/installation”, True)

  • 2)查看QGIS安装路径方法如下:

QgsApplication.prefixPath()

在QGIS的Python Console中输入上述命令可以返回Qgis使用的默认路径:如'D:/Program Files/QGIS 3.16.14/apps/qgis-ltr'
  • 3)配置完成后,我们通过调用 initQgis() 方法加载 QGIS 数据提供程序和图层注册表。第二个参数设置为 False,表示不使用 GUI,因为我们正在编写一个独立的脚本。

qgs.initQgis()

  • 4)结束程序

qgs.exitQgis()

2. 自定义程序使用PyQgis

在独立脚本中使用 PyQGIS 和自定义 PyQGIS 应用程序之间的唯一区别是实例化 QgsApplication 时的第二个参数。(True or False)

from qgis.core import *

# Supply the path to the qgis install location
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)

# Create a reference to the QgsApplication.
# Setting the second argument to True enables the GUI.  We need
# this since this is a custom application.

qgs = QgsApplication([], True)

# load providers
qgs.initQgis()

# Write your code here to load some layers, use processing
# algorithms, etc.

# Finally, exitQgis() is called to remove the
# provider and layer registries from memory
qgs.exitQgis()

3. 简单示例(OSM底图+图层加载)

import sys
import os

from pyqgis_note_1_ui import Ui_MainWindow

from qgis.core import *
from qgis.gui import *

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class MyWnd(QMainWindow, Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        # 初始化Ui
        self.setupUi(self)
        # 初始化Project和Canvas
        self.project = QgsProject.instance()
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        self.setCentralWidget(self.canvas)
        # 在Dock窗口中添加LayerTreeView
        self.vl = QVBoxLayout(self.dockWidgetContents)
        self.layer_tree_view = QgsLayerTreeView(self)
        self.vl.addWidget(self.layer_tree_view)
        self.layer_tree_root = self.project.layerTreeRoot()
        self.layer_tree_model = QgsLayerTreeModel(self.layer_tree_root)
        self.layer_tree_model.setFlag(QgsLayerTreeModel.AllowNodeRename)
        self.layer_tree_model.setFlag(QgsLayerTreeModel.AllowNodeReorder)
        self.layer_tree_model.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility)
        self.layer_tree_model.setFlag(QgsLayerTreeModel.ShowLegendAsTree)
        self.layer_tree_model.setAutoCollapseLegendNodes(10)
        self.layer_tree_view.setModel(self.layer_tree_model)
        self.layer_tree_bridge = QgsLayerTreeMapCanvasBridge(self.layer_tree_root, self.canvas)

        # 用于存放已加载的layers
        self.layers = []
        # 设置 Canvas CRS
        # crs = QgsCoordinateReferenceSystem("EPSG:3857")
        # self.canvas.setDestinationCrs(crs)

        # 加载WMS图层-OSM
        urlWithParams = 'https://tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0'
        self.osm_layer = QgsRasterLayer("type=xyz&url=" + urlWithParams, 'OSM', "wms")
        print('osm_crs', self.osm_layer.crs())
        if not self.osm_layer.isValid():
            print("OSM Layer failed to load!")
        else:
            self.project.addMapLayer(self.osm_layer)
            self.layers.append(self.osm_layer)
            self.canvas.setExtent(self.osm_layer.extent())
            self.canvas.setLayers(self.layers)

        self.actionOpenRaster = QAction("Raster", self)
        self.actionOpenVector = QAction("Vector", self)
        self.actionZoomIn = QAction("Zoom in", self)
        self.actionZoomOut = QAction("Zoom out", self)
        self.actionPan = QAction("Pan", self)

        self.actionZoomIn.setCheckable(True)
        self.actionZoomOut.setCheckable(True)
        self.actionPan.setCheckable(True)

        self.actionOpenRaster.triggered.connect(self.load_raster)
        self.actionOpenVector.triggered.connect(self.load_vector)
        self.actionZoomIn.triggered.connect(self.zoomIn)
        self.actionZoomOut.triggered.connect(self.zoomOut)
        self.actionPan.triggered.connect(self.pan)

        self.toolbar = self.addToolBar("Canvas actions")
        self.menuOpen = QMenu('Open', self.toolbar)
        self.toolbar.addAction(self.menuOpen.menuAction())
        self.menuOpen.addAction(self.actionOpenRaster)
        self.menuOpen.addAction(self.actionOpenVector)
        self.toolbar.addAction(self.actionZoomIn)
        self.toolbar.addAction(self.actionZoomOut)
        self.toolbar.addAction(self.actionPan)

        # create the map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(self.actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomIn.setAction(self.actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolZoomOut.setAction(self.actionZoomOut)
        self.pan()
    def load_raster(self):
        # 加载栅格图层
        path_to_tif, ext = QFileDialog.getOpenFileName(self, '打开', '',
                                                       '所有文件(*.tif)')  # "D:\QgisDemo\MYD11C1.A2019134.061.2020352180203.tif"
        rlayer = QgsRasterLayer(path_to_tif, os.path.basename(path_to_tif))
        if not rlayer.isValid():
            print("rLayer failed to load!")
        self.project.addMapLayer(rlayer)
        self.layers.append(rlayer)
        self.canvas.setExtent(rlayer.extent())
        self.canvas.setLayers(self.layers)
    def load_vector(self):
        # 加载矢量图层
        path_to_tif, ext = QFileDialog.getOpenFileName(self, '打开', '', '所有文件(*.shp)')
        layer = QgsVectorLayer(path_to_tif, os.path.basename(path_to_tif), 'ogr')
        if not layer.isValid():
            print("vLayer failed to load!")
        self.project.addMapLayer(layer)
        self.layers.append(layer)
        self.canvas.setExtent(layer.extent())
        self.canvas.setLayers(self.layers)
    def zoomIn(self):
        self.canvas.setMapTool(self.toolZoomIn)
    def zoomOut(self):
        self.canvas.setMapTool(self.toolZoomOut)
    def pan(self):
        self.canvas.setMapTool(self.toolPan)
if __name__ == '__main__':
    qgs = QgsApplication([], True)
    qgs.setPrefixPath('qgis', True)
    qgs.initQgis()

    window = MyWnd()
    window.show()

    exit_code = qgs.exec_()
    qgs.exitQgis()
    sys.exit(exit_code)

ui_demo为Qt Designer生成的python文件,可复制下述内容另存为.py,也可使用自己文件进行替换

# -*- coding: utf-8 -*-

################################################################################
## Form generated from reading UI file 'designeruJRilQ.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(u"gridLayout")

        MainWindow.setCentralWidget(self.centralwidget)

        self.dockWidget = QDockWidget(MainWindow)
        self.dockWidget.setObjectName(u"dockWidget")
        self.dockWidgetContents = QWidget()
        self.dockWidgetContents.setObjectName(u"dockWidgetContents")
        self.dockWidget.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget)

        self.retranslateUi(MainWindow)

        QMetaObject.connectSlotsByName(MainWindow)
    # setupUi

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
    # retranslateUi


4. 示例界面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值