1

Related Question Charts and Graphs that only display features in current extent Trying to write a custom function to return the current view extent. The below code is what I wrote based on the QGIS Cookbook https://docs.qgis.org/testing/pdf/en/QGIS-testing-PyQGISDeveloperCookbook-en.pdf. The return from the Output Preview is <built-in method xMinimum of QgsRectangle object at 0x000000... Any suggestions on where I am going wrong?

Function Code:

import math
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import QVariant
from PyQt4.QtGui import QAction, QMainWindow
canvas=QgsMapCanvas()
e=canvas.extent()
@qgsfunction(args=0, group='Custom', usesgeometry=True)
def CurrentExtent(value1, feature, parent):
    return str(e.xMinimum)+" "+str(e.yMaximum)+", "+str(e.xMaximum)+" "+str(e.yMaximum)+", "+str(e.xMaximum)+" "+str(e.yMinimum)+","+str(e.xMinimum)+" "+str(e.yMinimum)+"))"
1
  • You are calling the QgsMapCanvas class instead of calling the current map canvas. So replace:

    canvas=QgsMapCanvas()
    

    with

    canvas=iface.mapCanvas()
    

    You will also need to add the following import line:

    from qgis.utils import iface
    

  • When calling the extent funtions (i.e. e.xMaximum), you need to add parenthesis at the end (e.g. e.xMaximum()).

So your code could look like:

import math
from qgis.core import *
from qgis.gui import *
from qgis.utils import iface
from PyQt4.QtCore import QVariant
from PyQt4.QtGui import QAction, QMainWindow
canvas=iface.mapCanvas()
e=canvas.extent()
@qgsfunction(args=0, group='Custom', usesgeometry=True)
def CurrentExtent(value1, feature, parent):
    return str(e.xMinimum())+" "+str(e.yMaximum())+", "+str(e.xMaximum())+" "+str(e.yMaximum())+", "+str(e.xMaximum())+" "+str(e.yMinimum())+","+str(e.xMinimum())+" "+str(e.yMinimum())+"))"

enter image description here

  • @TylerVeinot - Most welcome, glad it worked :) – Joseph Nov 16 '18 at 10:30
  • Side question: After making the function and considered it working, I went ahead and made a filter expression using the new function. It seems to only return the extent as it was when I written the filter, it will not recalculate the extent as I pan around. In order to update the extent value I have to go in and delete CurrentExtent() and rewrite it in order to update. Actually if I just delete the ) in "()" and retype it it will also return the new current extent. – Tyler Veinot Nov 27 '18 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.