[Qgis-developer] PyQGIS Cookbook,
MySQL geometries and Graduated symbol renderer
Germán Carrillo
carrillo.german at gmail.com
Sun Feb 27 20:17:26 EST 2011
Hi Martin,
I would like to propose a couple of Python snippets to be included in the
PyQGIS Cookbook.
1) Load of MySQL geometries:
----------------------
uri =
"MySQL:dbname,host=localhost,port=3306,user=root,password=xxx|layername=my_table"
vLayer = QgsVectorLayer( uri, 'my_table', 'ogr' )
----------------------
BTW, I'm not sure if it is the best way to do it, but it works.
2) Graduated symbol renderer (Old symbology):
----------------------
fieldName = "My_Field"
numberOfClasses = 5
mFieldMap = {}
# Get the field index based on the field name
fields = layer.pendingFields()
for ( key, field ) in fields.iteritems():
if field.type() == QVariant.Int or field.type() == QVariant.Double:
mFieldMap[ str( field.name() ) ] = key
fieldIndex = mFieldMap[ fieldName ]
# Create the renderer object
renderer = QgsGraduatedSymbolRenderer( layer.geometryType() )
renderer.setMode( QgsGraduatedSymbolRenderer.EqualInterval ) #
EqualInterval/Quantile/Empty
# Prepare the required symbol objects
symbolList = []
geom = layer.geometryType()
provider = layer.dataProvider()
for i in range( numberOfClasses ):
symbol = QgsSymbol( geom )
brush = QBrush()
brush.setColor( self.randomColor() )
brush.setStyle( Qt.SolidPattern )
symbol.setBrush( brush )
symbolList.append( symbol )
# Define classes
minimum = provider.minimumValue( fieldIndex ).toDouble()[ 0 ]
maximum = provider.maximumValue( fieldIndex ).toDouble()[ 0 ]
for i in range( numberOfClasses ):
# Switch if attribute is int or double
lower = ('%.*f' % (2, minimum + ( maximum - minimum ) / numberOfClasses
* i ) )
upper = ('%.*f' % (2, minimum + ( maximum - minimum ) / numberOfClasses
* ( i + 1 ) ) )
lowerString = QVariant( lower ).toString()
upperString = QVariant( upper ).toString()
symbolList[ i ].setLowerValue( lowerString )
symbolList[ i ].setUpperValue( upperString )
symbolList[ i ].setLabel( lowerString + " - " + upperString )
# Define a symbol object based on each class
for i in range( numberOfClasses ):
symbol = symbolList[ i ]
lower_bound = symbol.lowerValue()
upper_bound = symbol.upperValue()
label = symbol.label()
sy = QgsSymbol( layer.geometryType(), lower_bound, upper_bound, label )
sy.setFillColor( symbol.brush().color() )
sy.setFillStyle( symbol.brush().style() )
renderer.addSymbol( sy )
renderer.setClassificationField( fieldIndex )
layer.setRenderer( renderer )
----------------------
Regards,
Germán
--
-----------
|\__
(:>__)(
|/
Soluciones Geoinformáticas Libres
http://geotux.tuxfamily.org/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/qgis-developer/attachments/20110227/35d41255/attachment.html
More information about the Qgis-developer
mailing list