I've got a question about .showAttributeTables() - i'm trying to open two attrbute tables at the end of a query (selection of lines within a polygon layer) - I thought I could simply do somthing like this
# Spatial selection
cm_line = QgsProject.instance().mapLayersByName("t_line")[0]
poly = QgsProject.instance().mapLayersByName("t_poly")[0]
for i in cm_line.getFeatures():
for l in poly.getFeatures():
if i.geometry().within(l.geometry()):
# add the selection to the layer
cm_line.select(i.id())
# open tables
layer = QgsProject().instance().mapLayersByName('t_poly')[0]
iface.showAttributeTable(iface.activeLayer())
layer = QgsProject().instance().mapLayersByName('t_line')[0]
iface.showAttributeTable(iface.activeLayer())
But this opens the same table twice (the first one) - But I thought i'd changed the active layer here :
layer = QgsProject().instance().mapLayersByName("t_line")[0]
??
Well, at least I didn't get an error message!
I should note that I've already seen this : Opening attribute table using PyQgis?
and this tutorial here: pyqgis-101-viewing-vector-layer-attributes
2 Answers 2
What you have in your own answer will work fine, but you could save yourself some typing (brevity & simplicity in code is a good thing and laziness is actually a useful trait for programmers!)
Since you already assigned both your layers to variables, you can simply do:
iface.showAttributeTable(cm_line)
iface.showAttributeTable(poly)
And just some additional info:
In the code you posted in your question, you were showing the attribute table for the active layer. That is whichever layer is highlighted in the layers panel, not the layer you were assigning to your layer
variable. Making a layer active is usually achieved by clicking on its name in the layers panel, but you can also set it programmatically:
iface.setActiveLayer(cm_line) #pass a QgsMapLayer object
-
Thanks that helps, I like simple :) I think I was confusing accessing a layer ('QgsProject().instance().mapLayersByName()[0]') and activating layers (i.e. 'iface.setActiveLayer(cm_line)') .howhow– howhow2019年02月18日 10:54:24 +00:00Commented Feb 18, 2019 at 10:54
Actually I think I've worked this out myself in the end:
# spatial selection
cm_line = QgsProject.instance().mapLayersByName("t_line")[0]
poly = QgsProject.instance().mapLayersByName("t_poly")[0]
for i in cm_line.getFeatures():
for l in poly.getFeatures():
if i.geometry().within(l.geometry()):
# add the selection to the layer
cm_line.select(i.id())
# Open attrib tables
iface.showAttributeTable(QgsProject().instance().mapLayersByName('t_poly')[0])
iface.showAttributeTable(QgsProject().instance().mapLayersByName('t_line')[0])
It works fine in anycase! But would still be interested to hear if anyone has alternative solutions?
Explore related questions
See similar questions with these tags.