Wednesday 31 January 2018

pyqgis - "Select by Attribute" in QGIS using python?


Is there a way to use the function "Select by Attribute" in QGIS using a python command? In my plugin the user should enter a value via a GUI and this value should be used in a function which selects all features which have this attribute. The column name is fixed in the code, the function should only search for the correct value.


In my current solution the function connects QGIS to a PostgreSQL database and runs an SQL statement. This creates a table from the result and the table is visualised as Shapefile in QGIS.


In principal it would be enough to highlight the features and not to create a new Shapefile of the selection. Using the "Select by Attribute" function would also skip the unnecessary database connection.


Is there a way to use the function "Select by Attribute" in python so that the features are highlighted? Using the function in QGIS all features that doesn't match the query are temporary blanked-out that would be ok too.



Answer



Yes. You can get all the attributes through the python bindings and implement extra filtering in your own plugin. See this PyQGIS Coobook excerpt for the rundown and some examples. You would then just exclude any nonmatching results from the returned dictionary.


As for the visualisation, you'll likely still have to create another layer, as select() does not have fitting arguments. You can use a memory layer to avoid having to create physical files (more on that in the cookbook).



edit:


Actually, you can use selectedFeaturesIds() with setSelectedFeatures(ids) to change the selection to the subset you created. Quoting the implementation directly:


/** Get a copy of the user-selected features */  
QList selectedFeatures();

/** Return reference to identifiers of selected features */
const QSet &selectedFeaturesIds() const;

/** Change selection to the new set of features */
void setSelectedFeatures(const QSet &ids);

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...