Docs in progress for 'QGIS testing'. Visit https://docs.qgis.org/3.4 for QGIS 3.4 docs and translations.
有时需要从插件加载现有项目,或者在开发独立的QGIS Python应用程序时(更常见)(请参见: python应用程序 )
要将项目加载到当前的QGIS应用程序中,需要创建 QgsProject
班级。这是一个单例类,因此必须使用它 instance()
方法。你可以称之为 read()
方法,传递要加载的项目的路径:
# If you are not inside a QGIS console you first need to import
# qgis and PyQt classes you will use in this script as shown below:
from qgis.core import QgsProject
# Get the project instance
project = QgsProject.instance()
# Print the current project file name (might be empty in case no projects have been loaded)
print(project.fileName())
'/home/user/projects/my_qgis_project.qgs'
# Load another project
project.read('/home/user/projects/my_other_qgis_project.qgs')
print(project.fileName())
'/home/user/projects/my_other_qgis_project.qgs'
如果需要修改项目(例如添加或删除某些层)并保存更改,请调用 write()
项目实例的方法。这个 write()
方法还接受用于将项目保存到新位置的可选路径:
# Save the project to the same
project.write()
# ... or to a new file
project.write('/home/user/projects/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('/home/user/projects/my_other_qgis_project.qgs')