Blending colors in Qt

I found myself in need of blending two QColors in Qt using an alpha ratio. For some reason I don’t understand the Qt library does not provide this feature. However, it is fairly easy to create such a method yourself.

 * @brief Blend two colors.
 * @param color1 One of the colors to be blended.
 * @param color2 One of the colors to be blended.
 * @param ratio The ratio between the colors. 0.5 will give a 50-50 blend.
 * @return The blended color.
static QColor blendColors(const QColor& color1, const QColor& color2, qreal ratio)
    int r =*(1-ratio) +*ratio;
    int g =*(1-ratio) +*ratio;
    int b =*(1-ratio) +*ratio;
    return QColor(r, g, b, 255);

The parameter ratio specifies the weight of the colors when blending. A ratio of 0.8 will result in a blend of 20% color1 and 80% color2. A ratio of 0.5 will therefore be a 50-50 blend of the two colors.

Feel free to use this code for what ever you want.

Leave a Comment

Your email address will not be published.