7

Lets say I have created a custom QGIS function, like for example

from qgis.core import *
from qgis.gui import *
import urllib.request
import urllib
import json

@qgsfunction(args='auto', group='Custom')
def jsonfromurl(url, feature, parent):
    header = {"accept":"application/json"}
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(request)
    response_data = response.read()
    encoding = response.info().get_content_charset('utf-8')
    data = json.loads(response_data.decode(encoding))
    #txt = json.dumps(data) #uncomment this line to receive data as string. also change next line to: return txt
    return data

This function only works when evaluated against a feature. Otherwise it returns the preview No feature was found on this layer to evaluate the expression. and just nothing when applying it.

How can I change that function, so it also works if no feature is given. For example (used as expression) in a print layout text box or an empty layer?

Like here: Adding a textbox to a QGIS layout where I want to display the result from the request https://nominatim.openstreetmap.org/reverse?format=json&lat=51.6895477895927&lon=-0.43032246110111033&zoom=18&addressdetails=1.

enter image description here

Simply removing feature and/or parent seems not to work and as stated on https://howtoinqgis.wordpress.com/2017/05/20/how-to-create-custom-functions-in-qgis-using-the-function-editor/ these arguments are always needed.

1
  • I think a qgsfunction always takes a feature - how are you using this, may be it should be a plugin not an expression
    – Ian Turton
    Apr 7, 2021 at 16:52

1 Answer 1

13

The trick is to let QGIS know that you don't need to reference any layer's field inside your function. Of course, only if that's the case, like it is with your function.

You can do that by passing an extra parameter referenced_columns to the decorator, like this:

@qgsfunction(args='auto', group='Custom', referenced_columns=[])

Doing so on an empty layer, with the test URL you provide I get:

enter image description here

For reference, this is the documentation of such parameter:

: param referenced_columns: An array of attribute names that are required to run
                            this function. Defaults to [QgsFeatureRequest.ALL_ATTRIBUTES].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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