I want to be able to set the value of the alpha channel of the selected features' colors in order to see what's under those features.

This thread gives a good answer to set the color of the selected features using PyQGIS:
How to change the color of a selected feature with pyQGIS?

For example, this command will switch color of selected features from yellow (default) to red:

>>> iface.mapCanvas().setSelectionColor( QColor("red") )

enter image description hereenter image description here

But how to set up an alpha value if you want to see what's under (e.g. the base map) your selected features ?

1 Answer 1


You can use the .fromRgb() method of the QColor object, e.g.:

>>> iface.mapCanvas().setSelectionColor( QColor().fromRgb(255,0,0,255) )

Obviously, this will give the same as the red color above but if you set a lower value for alpha, you will then see underlying object, here some buildings and paths on a base map:

>>> iface.mapCanvas().setSelectionColor( QColor().fromRgb(255,0,0,128) )

enter image description here

Or for a fully transparent selection:

>>> iface.mapCanvas().setSelectionColor( QColor().fromRgb(255,0,0,0) )

enter image description here


PyQt5 QColor object: https://doc.qt.io/qtforpython-5/PySide2/QtGui/QColor.html

fromRgb() method: https://doc.qt.io/qtforpython-5/PySide2/QtGui/QColor.html#PySide2.QtGui.PySide2.QtGui.QColor.fromRgb

but this is not 100% clear to me because it states :

The alpha component of rgb is ignored (i.e. it is automatically set to 255), use the fromRgba() function to include the alpha-channel specified by the given QRgb value.

and the signature gives: def fromRgb (r, g, b[, a=255]) which I successfully tested above.

The fromRgba() method accept an integer only which you may figure out how to build. For example, you can see this corresponding int value using .rgba() on the QColor object:

>>> QColor().fromRgb(255,0,0,64).rgba()

This is my version info:

>>> import sys
>>> print(f"Python version: {sys.version}")
Python version: 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0]

>>> from PyQt5.QtCore import QT_VERSION_STR, PYQT_VERSION_STR
>>> print(f"Qt: {QT_VERSION_STR}\nPyQt: {PYQT_VERSION_STR}")
Qt: 5.15.3
PyQt: 5.15.6

Tested on QGIS 3.26.2-Buenos Aires.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.