有时您需要从插件中加载现有项目,或者在开发独立的QGIS Python应用程序中(更多)来加载现有项目(请参阅:Python Applications)。
要将项目加载到当前的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独立应用程序,则为了使加载的项目与画布同步,需要实例化a 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')
下一个
前一个
©版权所有2002-现在,QGIS项目 最近更新于2020年4月3日09:14。
使用Sphinx使用Read the Docs提供的主题构建。