Last active
August 27, 2018 10:53
-
-
Save geraldo/27884229955a93974713b882927567f9 to your computer and use it in GitHub Desktop.
QGIS 2 (python2) project file parser writing layer properties to JSON file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If you are not inside a QGIS console you first need to import | |
# qgis and PyQt5 classes you will use in this script as shown below: | |
from qgis.core import * | |
from PyQt4.QtCore import QFileInfo | |
import json | |
# create a reference to the QgsApplication, setting the | |
# second argument to False disables the GUI | |
qgs = QgsApplication([], False) | |
# supply path to qgis install location | |
qgs.setPrefixPath("/usr", True) | |
# load providers | |
qgs.initQgis() | |
# Get the project instance | |
project = QgsProject.instance() | |
# Load qgis project | |
project.read(QFileInfo('/home/gerald/Documents/poum.qgs')) | |
print "Project file:"+project.fileName() | |
print "Project title: "+project.title() | |
def layertree(node): | |
obj = {} | |
if isinstance(node, QgsLayerTreeLayer): | |
obj['name'] = node.layerName() | |
obj['id'] = node.layerId() | |
obj['type'] = "layer" | |
obj['indentifiable'] = node.layerId() not in nonidentify | |
obj['fields'] = [] | |
obj['actions'] = [] | |
#print "- layer: ", node.layerName() | |
layer = QgsMapLayerRegistry.instance().mapLayer(node.layerId()) | |
conf = layer.editFormConfig() | |
for field in layer.fields(): | |
if conf.widgetType(field.name()) != 'Hidden': | |
f = {} | |
f['name'] = field.name() | |
f['alias'] = field.alias() | |
f['type'] = field.typeName() | |
obj['fields'].append(f) | |
for action in layer.actions().listActions(): | |
a = {} | |
a['name'] = action.name() | |
a['action'] = action.action() | |
obj['actions'].append(a) | |
return obj | |
elif isinstance(node, QgsLayerTreeGroup): | |
obj['name'] = node.name() | |
obj['type'] = "group" | |
obj['children'] = [] | |
#print "- group: " ,node.name() | |
for child in node.children(): | |
obj['children'].append(layertree(child)) | |
return obj | |
info=[] | |
print "Project tree:" | |
nonidentify = project.nonIdentifiableLayers() | |
root = project.layerTreeRoot() | |
for group in root.children(): | |
obj = layertree(group) | |
info.append(obj) | |
# identifiable <Identify> | |
#print project.readEntry("qgis", "Identify") | |
# write to json file | |
f=open('info.json', 'w+') | |
f.write(json.dumps(info)) | |
f.close() | |
# When your script is complete, call exitQgis() to remove the | |
# provider and layer registries from memory | |
qgs.exitQgis() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment