Search code examples
c++qtrgbqcolor

How to get QColor::greenF color value exactly between 0 and 1 instead of rounding off?


I have a QColor value and I need to break it down into its RGB components between 0 and 1 with only one value after decimal point.
For example: Orange color is

QColor color = QColor(255,128,0)
qreal green = color.greenF();
qDebug() << green; //0.501960784

Whereas the green component must be 0.6. That is, it's rgb value is (255,128,0) or (1,0.6,0).

How to get 0.6 instead of 0.501960784?


Solution

  • But Orange color is 255,128,0

    There is no such thing as "the" orange color. Everyone calls something else using the same word. Orange isn't a color, it's a range of hues. Those hues become colors once you assign them some saturation and brightness. There's a whole lot of colors that can be represented using an 8-bit-per-componet R,G,B triple that all have a hue that is orange, and that thus qualify as an orange. There's no the orange,

    Whereas the green component must be 0.6. That is, it's rgb value is (255,128,0) or (1,0.6,0).

    It's not. QColor tells you so, and basic math tells you so. The color clearly is 1/0.6/0, or 1*255, 6/10*255, 0*255, or 255, 1530/10, 0 or 255, 153, 0 exactly. It won't ever be 255,128,0 and I have no idea who told you that, but they were wrong.

    So it's really simple: forget it all. Just use QColor::redF, greenF and blueF. They work the way they should.

    Oh, and you didn't even mention the elephants in the room that are color spaces. An RGB triple has no physical meaning - it's entirely abstract - until you map it to a physical color space. And you better use calibrated output devices to interface your color choice with the user, otherwise it'll be endless silliness all around.