2. PyQGIS Windows下开发环境搭建

发布于:2025-05-23 ⋅ 阅读:(22) ⋅ 点赞:(0)

前言

开发环境搭建

QGis说明

  • QGis安装完成后目录如下
    在这里插入图片描述

  • 打开QGIS Desktop,并能显示Python console即可

在这里插入图片描述

PyQGis环境说明

  • 在QGis安装目录中有Python环境,如下图
    在这里插入图片描述

  • 在QGis安装目录的bin中有设置环境变量的脚本,如下图
    在这里插入图片描述

  • 在 Python 中,PYTHONPATH 是一个环境变量,用于指定导入 Python 模块时要搜索的目录列表。

  • python-qgis-ltr-dev.bat用于设置python相关变量

@echo off
call "%~dp0\o4w_env.bat"
@echo off
path %OSGEO4W_ROOT%\apps\qgis-ltr-dev\bin;%PATH%
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT:\=/%/apps/qgis-ltr-dev
set GDAL_FILENAME_IS_UTF8=YES
rem Set VSI cache to be used as buffer, see #6448
set VSI_CACHE=TRUE
set VSI_CACHE_SIZE=1000000
set QT_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\qgis-ltr-dev\qtplugins;%OSGEO4W_ROOT%\apps\qt5\plugins
set PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis-ltr-dev\python;%PYTHONPATH%
python %*

  • 该脚本会设置QGIS_PREFIX_PATH QT_PLUGIN_PATH PYTHONPATH等变量

  • 脚本中set PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis-ltr-dev\python;%PYTHONPATH%将qgis-ltr-dev的python目录加入python模块搜索列表
    在这里插入图片描述

  • 运行脚本之后,可以在python中可以导入QGis的模块并调用函数,如下图
    在这里插入图片描述

from qgis.core import Qgis
print(Qgis.releaseName())

PyCharm Community Edition

PyCharm Community下载地址

配置pycharm

  1. 配置python解释器路径: C:\OSGeo4W\bin\python-qgis-ltr-dev.bat
    在这里插入图片描述

  2. 配置pyuic:.ui文件转换为py文件
    在这里插入图片描述

  3. 配置pyrcc:.qrc文件转换成py文件
    在这里插入图片描述

  4. 配置Qt Designer New:用于新建ui
    在这里插入图片描述

  5. 配置Qt Designer Edit:用于编辑已有ui
    在这里插入图片描述

  • MyDesigner.bat文件命令内容如下
@echo off
rem Root OSGEO4W home dir to the same directory this script exists in
call "%~dp0\bin\o4w_env.bat"

%~dp0\apps\Qt5\bin\designer.exe %~1%

HelloPyQGis增加Qt Gui

在这里插入图片描述

  • 增加MainWindow.ui,添加QLabel用于显示QGis ReleaseName
    在这里插入图片描述

在这里插入图片描述

  • Pyuic5将MainWindow.ui转换为MainWindow.py
    在这里插入图片描述
    在这里插入图片描述

  • 添加py文件:mymainwindow.py,代码如下,注意MainWindow继承了QMainWindow和Ui_MainWindow

from PyQt5.QtWidgets import QMainWindow
from ui.MainWindow import Ui_MainWindow

from qgis.core import Qgis

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.label.setText(Qgis.version())
  • 修改main.py,代码如下,注意QgsApplication.setPrefixPath需要设置对应的路径
import platform

from PyQt5.QtCore import Qt
from qgis.core import QgsApplication

from mymainwindow import MainWindow

if __name__ == '__main__':
    qgis_installation = ""
    sys = platform.system()
    if sys == "Windows":
        qgis_installation = r"C:/OSGeo4W/apps/qgis-ltr-dev"
    elif sys == "Linux":
        qgis_installation = r"/home/t/dev/cpp/apps/qgis"

    QgsApplication.setPrefixPath(qgis_installation, True)
    QgsApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QgsApplication([], True)
    app.initQgis()
    mainWindow = MainWindow()
    mainWindow.show()
    app.exec_()
    app.exitQgis()
  • 如果需要修改MainWindow.ui,可以运行Qt Designer Edit
    在这里插入图片描述

  • 运行即可
    在这里插入图片描述

总结

  • 介绍了Windows下使用Pycharm搭建PyQGis开发环境的过程

网站公告

今日签到

点亮在社区的每一天
去签到