Using the advanced filter of an attribute table from python

QGIS Python Editor version:

from qgis.PyQt.QtGui import *

layer = iface.activeLayer()

attDialog = iface.showAttributeTable(layer)

# firstly, you need get some widgets
mFilterButton = attDialog.findChild(QToolButton,'mFilterButton')
mActionAdvancedFilter = attDialog.findChild(QAction,'mActionAdvancedFilter')
mFilterQuery = attDialog.findChild(QLineEdit,'mFilterQuery')
mActionApplyFilter = attDialog.findChild(QAction,'mActionApplyFilter')

# set checked Advanced Filter (Expression)
mFilterButton.setDefaultAction(mActionAdvancedFilter)

# You can use string version of request
request = u'"STATUS" = \'OK\'' 
# add query string to the text box
mFilterQuery.setText(request)
mFilterQuery.setVisible(True)

# apply query
mActionApplyFilter.trigger()

enter image description here

Plugin version:

self.attDialog = self.iface.showAttributeTable(self.layer)

mFilterButton = self.attDialog.findChild(QToolButton,'mFilterButton')
mActionAdvancedFilter = self.attDialog.findChild(QAction,'mActionAdvancedFilter')
mFilterQuery = self.attDialog.findChild(QLineEdit,'mFilterQuery')
mActionApplyFilter = self.attDialog.findChild(QAction,'mActionApplyFilter')

...
...

Either

You can pass the expression string directly to the selectByExpression() method of your QgsVectorLayer instance like this:

self.layer.selectByExpression('"STATUS" = \'OK\'')

u'...' is not needed since everything is unicode in Python 3.

Then you show the attribute table as shown above

self.attDialog = self.iface.showAttributeTable(self.layer)

and set its behaviour to only show the selected features

self.attDialog.findChild(QAction,'mActionSelectedFilter').trigger()

cp. PyQGIS Attribute table show selected features

Or

If working with selections is unwanted one may apply a filter to the layer by

self.layer.setSubsetString(''"STATUS" = \'OK\''')

and open the attribute table.

Delete the filter by

self.layer.setSubsetString('')

Note that subset strings are plain sql.

cp. https://qgis.org/api/classQgsVectorLayer.html#aba0ee124dcf2d037f3af53d99866c01c

Tags:

Pyqgis 3