I have added a QgsLegend::selectedLayers() binding to QgsLegendInterface in master branch. You can now do the following when using a current master build (might have to wait a day or two, unless compiling yourself; not going to be backported to QGIS 1.8):
# iface.legendInterface().selectedLayers(bool inDrawOrder)
# param inDrawOrder False returns QTreeWidget::selectedItems() order
# True returns render drawing order (Legend or Layer Order)
# returns list of selected QgsMapLayer(s), or empty list
from qgis.utils import iface
li = iface.legendInterface()
sl = li.selectedLayers(True)
for lyr in sl:
print lyr.name()
You can use the solutions given in Using processing algorithms from the console:
But if you look at what's in the module (version 2.2):
import processing
dir(processing)
no more getfeatures()
or getFeatures()
You can control this with a little function adapted from Script de Python para filtrar por patrón de texto los métodos de Clases en PyQGIS de José Guerrero
import re
def get_patt(keyword, L):
return [item for item in dir(L) if re.search(keyword,item)]
get_patt("getfeatures",processing)
[]
get_patt("getFeatures",processing)
[]
but there is:
get_patt("features",processing)
['features']
So the command is:
features = processing.features(layer)
But for me, it is easiest with:
without processing:
layer = qgis.utils.iface.activeLayer()
with processing:
layer = processing.getObject("name_of_the_layer")
All the features:
for feat in layer.getFeatures():
geom= feat.geometry()
attr =feat.attributes()
Selected features only:
for feat in layer.selectedFeatures():
geom= feat.geometry()
attr =feat.attributes()
and, for example, an "universal solution":
if layer.selectedFeatureCount():
geom = [feat.geometry() for feat in layer.selectedFeatures()]
else:
geom = [feat.geometry() for feat in layer.getFeatures()]
Best Answer
The original question was referred to QGIS 2.x version.
QGIS 3.x
To get the layers selected in the TOC in QGIS 3.x check this answer.
QGIS 2.x
You can get the layers selected in the TOC with something like this
the
selectedLayers()
method in QgsLegendInterface does the trick. But take into account that:selectedLayers()
. You must select it in the GUI one by one.A more complete example: