Cheat sheet for PyQgis
Access Canvas
canvas = iface.mapCanvas()
Access checked Layers
iface.mapCanvas().layers()
Obtain Layers name
canvas = iface.mapCanvas()
layers = [canvas.layer(i) for i in range(canvas.layerCount())]
layers_names = [ layer.name() for layer in layers ]
print "layers TOC = ", layers_names
Obtain Layers name from PostGIS database
from PyQt4.QtSql import *
db = QSqlDatabase.addDatabase("QPSQL");
db.setHostName("localhost");
db.setDatabaseName("postgres");
db.setUserName("postgres");
db.setPassword("postgres");
db.open();
names=db.tables( QSql.Tables)
print names
Add vector layer
layer = iface.addVectorLayer("input.shp", "name", "ogr")
if not layer:
print "Layer failed to load!"
Find layer by name
from qgis.core import QgsMapLayerRegistry
layer = QgsMapLayerRegistry.instance().mapLayersByName("name")[0]
print layer.name()
Set Active layer
from qgis.core import QgsMapLayerRegistry
layer = QgsMapLayerRegistry.instance().mapLayersByName("name")[0]
iface.setActiveLayer(layer)
Remove all layers
QgsMapLayerRegistry.instance().removeAllMapLayers()
Adding a button on toolbar
from PyQt4.QtGui import QToolButton, QIcon
button = QToolButton()
button.setIcon(QIcon("PATH-TO-FILE"))
iface.addToolBarWidget(button)
OR (Using iface)
from PyQt4.QtGui import QToolButton, QIcon
iface.toolButton = QToolButton()
boton.setIcon(QIcon("C:/Users/enocc/Desktop/bolt3.png"))
iface.addToolBarWidget(iface.toolButton)
Adding a progress bar
from PyQt4.QtGui import QProgressDialog, QProgressBar
def progdialog(progress):
dialog = QProgressDialog()
dialog.setWindowTitle("En progreso...")
dialog.setLabelText("Cargando...")
bar = QProgressBar(dialog)
bar.setTextVisible(True)
bar.setValue(progress)
dialog.setBar(bar)
dialog.setMinimumWidth(300)
dialog.show()
return dialog, bar
def calc(x, y):
dialog, bar = progdialog(0)
bar.setValue(0)
bar.setMaximum(100)
sum = 0
progress = 0
for i in range(x):
for j in range(y):
k = i + j
sum += k
i += 1
progress = (float(i) / float(x)) * 100
bar.setValue(progress)
print sum
calc(10000, 2000)
Get algorithms list
import processing
processing.alglist()
Get algorithms Help
Random selection
processing.alghelp('qgis:randomselection')
Get algorithms Options
Random selection
processing.algoptions('qgis:randomselection')
http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/
https://stackoverflow.com/questions/tagged/qgis