[GIS] PyQGIS gives TypeError: QgsExpression.prepare(): argument 1 has unexpected type ‘QgsFields’

pyqgisqgis-3typeerror

This question is very related to the unanswered Retrieve features from QgsFieldExpressionWidget pyqgis

I have a layer and I've build a QgsExpression that involves a field of that layer. What I'm trying to do is to evaluate the expression and get the results as a single list.

The problem is that I'm trying to do this with QGIS master (so the future 3 version) and the instruction of the PyQGIS cookbook are outdated because some API are changed.

Just to have an example:

vl = iface.activeLayer()
exp = QgsExpression('PH > 7') # where PH is the name of a field
exp.prepare(vl.pendingFields())


# then I get this error

Traceback (most recent call last):
  File "/usr/lib/python3.5/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
TypeError: QgsExpression.prepare(): argument 1 has unexpected type 'QgsFields'

Someone has already successfully used the QgsExpression for QGIS master?

Best Answer

I used your code in my QGIS Python Console (with a shapefile with 'PH' field; only one value > 7) and I got a result (see next image).

enter image description here

So, I printed 'vl.pendingFields()' to find out what kind of object is:

>>>vl.pendingFields()
<qgis._core.QgsFields object at 0x17E10E40>

and afterward, a help for QgsExpression.prepare for corroborating wich parameters it uses:

help(QgsExpression.prepare)
Help on built-in function prepare:

prepare(...)
    QgsExpression.prepare(QgsFields) -> bool
    QgsExpression.prepare(QgsExpressionContext) -> bool

In my case, used parameter is correct and the result was as expected. So, I suggest that you use 'help' command with your QGIS future 3 version to find out the new kind of parameters to use.

Related Question