Q:

How to create a virtual layer in QGIS that shows only the features in the extent

I am trying to make a virtual layer that is based on a map layer that only returns the features in the current map canvas extent. The purpose is to setup a Data Graph that shows statistical data of only the features in the current map extent. I cannot find any examples of this being done in qgis or using SQL. Is it possible?

A:

The trick is to create a function that access QGIS graphical interface, and that is piped to the query of the virtual layer.
1) Open a function editor (from anywhere, including from field calculator) and create a new function that reads the canvas extent and returns it as a geometry.
from qgis.core import *
from qgis.gui import *
from qgis.utils import iface

@qgsfunction(args='auto', group='Custom')
def currentExtent(feature, parent):
    return QgsGeometry.fromRect(iface.mapCanvas().extent())

2) Create a new virtual layer and use the new function, selecting features that intersects the displayed area. To get features entirely within the displayed area, use ST_within instead.
SELECT * 
FROM mylayer
WHERE st_intersects(mylayer.geometry, currentExtent());

Note that if you have the attribute table open, you would need to click the refresh icon after panning the map.

