2. 正在加载项目
提示
如果您在pyqgis控制台之外,则此页面上的代码片段需要以下导入:
1from qgis.core import (
2 Qgis,
3 QgsProject,
4 QgsPathResolver
5)
6
7from qgis.gui import (
8 QgsLayerTreeMapCanvasBridge,
9)
有时,您需要从插件加载现有项目,或者(更常见的是)在开发独立的QGIS Python应用程序时加载现有项目(请参见: Python应用程序 )。
要将项目加载到当前QGIS应用程序中,您需要创建 QgsProject
班级。这是一个单例类,因此您必须使用其 instance()
方法来完成此操作。您可以将其称为 read()
方法,传递要加载的项目的路径:
1# If you are not inside a QGIS console you first need to import
2# qgis and PyQt classes you will use in this script as shown below:
3from qgis.core import QgsProject
4# Get the project instance
5project = QgsProject.instance()
6# Print the current project file name (might be empty in case no projects have been loaded)
7# print(project.fileName())
8
9# Load another project
10project.read('testdata/01_project.qgs')
11print(project.fileName())
testdata/01_project.qgs
如果需要对项目进行修改(例如添加或移除某些层)并保存更改,请调用 write()
项目实例的方法。这个 write()
方法还接受将项目保存到新位置的可选路径:
# Save the project to the same
project.write()
# ... or to a new file
project.write('testdata/my_new_qgis_project.qgs')
两者都有 read()
和 write()
函数返回一个布尔值,您可以使用该值检查操作是否成功。
备注
如果您正在编写QGIS独立应用程序,为了将加载的项目与画布同步,您需要实例化 QgsLayerTreeMapCanvasBridge
如下例所示:
bridge = QgsLayerTreeMapCanvasBridge( \
QgsProject.instance().layerTreeRoot(), canvas)
# Now you can safely load your project and see it in the canvas
project.read('testdata/my_new_qgis_project.qgs')
2.1. 解决错误路径
加载到项目中的图层可能会被移动到其他位置。当再次加载项目时,所有的层路径都会断开。这个 QgsPathResolver
类帮助您重写项目中的层路径。
它的 setPathPreprocessor()
方法允许设置自定义路径预处理器功能,以便在将路径和数据源解析为文件引用或图层源之前对其进行操作。
处理器函数必须接受单个字符串参数(表示原始文件路径或数据源),并返回该路径的已处理版本。调用路径预处理器函数 before 任何糟糕的层处理程序。如果设置了多个预处理器,则将根据它们最初设置的顺序依次调用它们。
以下是一些使用案例:
替换过时的路径:
def my_processor(path): return path.replace('c:/Users/ClintBarton/Documents/Projects', 'x:/Projects/') QgsPathResolver.setPathPreprocessor(my_processor)
用新的数据库主机地址替换数据库主机地址:
def my_processor(path): return path.replace('host=10.1.1.115', 'host=10.1.1.116') QgsPathResolver.setPathPreprocessor(my_processor)
将存储的数据库凭据替换为新凭据:
1def my_processor(path): 2 path= path.replace("user='gis_team'", "user='team_awesome'") 3 path = path.replace("password='cats'", "password='g7as!m*'") 4 return path 5 6QgsPathResolver.setPathPreprocessor(my_processor)
同样,一个 setPathWriter()
方法可用于路径写入器函数。
将路径替换为变量的示例:
def my_processor(path):
return path.replace('c:/Users/ClintBarton/Documents/Projects', '$projectdir$')
QgsPathResolver.setPathWriter(my_processor)
这两个方法都返回一个 id
这可以用来删除他们添加的预处理器或编写器。看见 removePathPreprocessor()
和 removePathWriter()
。
2.2. 使用标志来加快速度
在某些情况下,您可能不需要使用功能齐全的项目,而只是出于特定原因想要访问它,标记可能会很有帮助。有关旗帜的完整列表,请参阅 ProjectReadFlag
。可以将多个标志添加到一起。
例如,如果我们不关心实际的图层和数据,而只是想访问项目(例如,用于布局或3D视图设置),则可以使用 DontResolveLayers
用于绕过数据验证步骤并防止出现坏层对话框的标志。可以执行以下操作:
readflags = Qgis.ProjectReadFlags()
readflags |= Qgis.ProjectReadFlag.DontResolveLayers
project = QgsProject()
project.read('C:/Users/ClintBarton/Documents/Projects/mysweetproject.qgs', readflags)
要添加更多标志,请使用python位或运算符 (|
)必须使用。