I'm trying to understand the QGIS Python API documentation - as an example I want to get the number of features with a specified legend key, but I don't get the correct result.
Under the layer
variable I have a vector layer. To get a number of all features in the layer I call layer.featureCount()
and I get the correct number.
Everything is fine, but now the fun starts when I want to fill in the legendKey
parameter. The docs say that featureCount
gets a legendKey
parameter which is a string. So I try to pass my legendKey
as a string:
layer.featureCount('myvalue')
which gives me -1. But in the layer, I have one feature whose value is equal to 'myvalue'.
Maybe that's not how I have to pass the string legendKey
argument. So I try:
layer.featureCount(' "my_field" = \'myvalue\' ')
as maybe it will be the correct string to pass, but it still gives me -1.
I read the docs and it says:
Features must be first calculated by
countSymbolFeatures()
Ok, so I calculate features with this method:
ftCounter = layer.countSymbolFeatures()
it returns QgsVectorLayerFeatureCounter
. This class also has featureCount()
method. So I try to call this method on the returned feature counter object:
ftCounter.featureCount()
and it gives me AttributeError
:
'NoneType' object has no attribute 'featureCount'.
It turns out that under ftCounter
I have nothing, None. The docs say it creates a new feature counter for the layer.
Maybe I have to create a feature counter by passing another argument as the docs of this class specify it - pass layer and context. After googling how to create exp. context I create smth like this:
exp = QgsExpression('"my_field" = \'myvalue\'')
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
ftCounter = QgsVectorLayerFeatureCounter(layer, context)
ftCounter.featureCount()
and I get TypeError
:
QgsVectorLayerFeatureCounter.featureCount()`: not enough arguments.
So maybe now I have to pass this required string legendKey
argument:
ftCounter.featureCount('"my_field" = \'muvalue\'')
Nope, it gave me -1.
Maybe I misunderstood the legendKey string parameter at the beginning but my core question is how to learn from QGIS Python API as it turns out to be one big maze and the only way to understand it is to copy&paste somebody's else working code as a solution. But as in my above example even with some googling I still don't get it.