Last active
October 21, 2021 16:53
-
-
Save nick4rivers/d2771cf52e8e0795845a3f69ad84843c to your computer and use it in GitHub Desktop.
PyQGIS duplicate a layer, set a filter, and set a layer variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # how to duplicate or clone a map layer | |
| # renaming the map layer and setting a filter | |
| # and also setting a variable on a layer for use in scripts | |
| # also shows how to connnect a .qml to a map layer | |
| # Select a layer that is already added to the interface | |
| layer_original = QgsProject.instance().mapLayersByName('original')[0] | |
| # duplicate or clone the layer | |
| layer_cloned = layer_original.clone() | |
| # add it to the map | |
| QgsProject.instance().addMapLayer(layer_cloned) | |
| # set a name for the duplicate layer | |
| layer_cloned.setName('layer_cloned') | |
| # set a layer filter, in this case to just a parent table id | |
| layer_cloned.setSubsetString("parent_id = 42") | |
| # load a custom .qml for styling, forms, etc.... | |
| layer_cloned.loadNamedStyle('my_path/layer_style.qml') | |
| # set a variable that would become the parent id, could be used as default value when creating a new record | |
| QgsExpressionContextUtils.setLayerVariable(layer_cloned,'parent_id', 42) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment