QColor
can return rgba values of type int
(32-bit signed integer). Why is that? The color values range from 0-255, don't they? Is there any situation where this might not be the case?
I'm considering to implicitly cast each of the rgba values returned by QColor.red()/green()/blue()/alpha()
to quint8
. It seems to work but I don't know if this will lead to problems in some cases. Any ideas?
I assume you are talking about
QColor::rgba()
which returns aQRgb
.QRgb
is an alias to unsigned int. In these 32 bits all fours channels are encoded as#AARRGGBB
, 8 bits each one (0-255, as you mentioned). So, a color like alpha=32, red=255, blue=127, green=0 would be0x20FF7F00
(553615104
in decimal).Now, regarding your question about casting to
quint8
, there should be no problem since each channel is guaranteed to be in the range 0..255 (reference). In general, Qt usually usesint
as a general integer and do not pay too much attention to the width of the data type, unless in some specific situations (like when it is necessary for a given memory access, for example). So, do not worry about that.Now, if these operations are done frequently in a high performance context, think about retrieving the 32 bits once using
QColor::rgba
and then extract the components from it. You can access the individual channels using bitwise operations, or through the convenience functionsqAlpha
,qRed
,qBlue
andqGreen
.For completeness, just to mention that the sibbling
QColor::rgb
method returns the same structure but the alpha channel is opaque (0xFF). You also haveQColor::rgba64
, which returns aQRgba64
. It uses 16 bits per channel, for higher precision. You have the 64 bits equivalents toqAlpha
, etc, asqAlpha64
and so on.