前言
- 介绍在Windows搭建pyqgis开发环境
- ide使用pycharm community
- QGis安装参考教程1. qgis二次开发环境搭建(qgis-3.28.6+qt5.15)
- 说明:文章中的示例代码均来自开源项目qgis_py_api_apps
开发环境搭建
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
配置python解释器路径:
C:\OSGeo4W\bin\python-qgis-ltr-dev.bat
配置pyuic:.ui文件转换为py文件
配置pyrcc:.qrc文件转换成py文件
配置Qt Designer New:用于新建ui
配置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开发环境的过程