Is there a QGIS Python binding for generating a grid programmatically without using the GUI?
Best Answer
From an existing layer:
1) you can use processing with the algorithm "qgis:creategrid" as in the "Hex grid from layer bounds" in Processing/Scripts/Example scripts. (look at Processing-Help / qgis / creategrid.rst)
In general you should look at this page of the APIs documentation. As a working example see as follows:
vl = iface.activeLayer()
## get default style
myStyle = QgsStyleV2().defaultStyle()
## get a list of default color ramps [u'Blues', u'BrBG', u'BuGn'....]
defaultColorRampNames = myStyle.colorRampNames()
## setting ramp to Blues, first index of defaultColorRampNames
ramp = myStyle.colorRamp(defaultColorRampNames[0])
# set up an empty categorized renderer and assign the color ramp
renderer = QgsCategorizedSymbolRendererV2(field, [])
renderer.setSourceColorRamp(ramp)
vl.setRendererV2(renderer)
Best Answer
From an existing layer:
1) you can use processing with the algorithm "qgis:creategrid" as in the "Hex grid from layer bounds" in Processing/Scripts/Example scripts. (look at Processing-Help / qgis / creategrid.rst)squared grid
rectangular grid
For other types of grids change the value in runalg (0,1,2,3 = Rectangle (line), Rectangle (polygon), Diamond (polygon), Hexagon (polygon)):
For Hexagonal grid
2) You can adapt the script of ustroetz in Create a square grid polygon shapefile with python
part of my class to create a memory layer limited here to the geometry of Polygons:
The script to create a squared grid layer from an existing layer:
Result:
But you can modify the script using numpy in place of math ceil and int
and if you don't understand xmin,ymin,xmax,ymax = layer.extent().toRectF().getCoords()
and to go faster, you can even use the gridding functions of numpy