3

I can select a layer using:

lyr = QgsProject.instance().mapLayersByName( "lyr_name" )[0]
iface.setActiveLayer(lyr)

This selects and highlights the layer in the table of contents.

How can I deselect it so that it is no longer highlighted?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
jim
  • 55
  • 5

2 Answers2

5

To remove the blue / grey selection on the layer in the layer tree view, you can do it with the following code :

### your code ###
lyr = QgsProject.instance().mapLayersByName( "world" )[0]
iface.setActiveLayer(lyr)
#################

get the Qgis layer tree view (QgsLayerTreeView)

lyr_tree = iface.layerTreeView()

deselect all the layers

lyr_tree.setCurrentLayer(None)

or faster with

iface.layerTreeView().setCurrentLayer(None)


Links :

J. Monticolo
  • 15,695
  • 1
  • 29
  • 64
1

You can do deselect your selected features with the method removeSelection() :

lyr = QgsProject.instance().mapLayersByName("lyr_name")[0]
lyr.removeSelection()

You can also use mActionDeselectAll. Take a look at this code : https://gis.stackexchange.com/a/155726/197233?

enter image description here

Timeless.
  • 644
  • 4
  • 13