PyQgisCookbook--加载项目(三)


有时您需要从插件中加载现有项目,或者在开发独立的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提供的主题构建。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值