5

As explained by @xunilk in Getting attribute values from vector features visible in QGIS canvas using PyQGIS we can easily access to the attribute values of the features visible in the QGIS canvas (code below)

layer = iface.activeLayer()
mapcanvas = iface.mapCanvas()
rect = mapcanvas.extent()

request = QgsFeatureRequest().setFilterRect(rect)

selected_feats = layer.getFeatures(request)

attr = [ feat.attributes() for feat in selected_feats ]

print(attr)

However I'm struggling to find a way to display, in the attribute table, only the values of the visible features.

Do you have any suggestions?

Taras
  • 32,823
  • 4
  • 66
  • 137
wanderzen
  • 2,130
  • 6
  • 26

2 Answers2

8

I dont know what can be done in plugins and not, but in QGIS you can apply a filter:

layer = iface.activeLayer()
mapcanvas = iface.mapCanvas()
rect = mapcanvas.extent()
request = QgsFeatureRequest().setFilterRect(rect)
selected_feats = layer.getFeatures(request)

ids = [f.id() for f in selected_feats] where_clause = '"id" IN{0}'.format(tuple(ids)) layer.setSubsetString(where_clause)

BERA
  • 72,339
  • 13
  • 72
  • 161
  • 1
    Perfect @BERA that's exactly what I was looking for ! I just changed the ids variable with ids = [f["target_field"] for f in selected_feats] to match my need ! – wanderzen Apr 06 '22 at 14:03
5

This solution will open the attribute table with selected features within the canvas. It requires installation of the pyautogui package.

import pyautogui

layer = iface.activeLayer()

extent = iface.mapCanvas().extent()

layer.selectByRect(extent)

pyautogui.hotkey('Ctrl', 'F6')


This solution will create a new layer out of the selection within the canvas.

layer = iface.activeLayer()

extent = iface.mapCanvas().extent()

layer.selectByRect(extent)

temp_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.selectedFeatureIds()))

QgsProject.instance().addMapLayer(temp_layer)


References:

Taras
  • 32,823
  • 4
  • 66
  • 137