Qt: Tint alphatransparent PNG (September 21, 2011)
Let’s assume you want to display the logo of your company in your Qt app. Most probably that logo has just single color with an alpha channel.But: Having the color hard coded in the image is not nice, there are users (like me!) out there, who use a custom (dark!) color scheme. Meaning: If your logo is black/dark and assumes a bright background and you just embed it blindly in your app, I probably won’t see it since the background will be dark in my case.
Here is a solution for the simple case of a mono-colored PNG with an alpha channel which I came up with:
QLabel* label = new QLabel;
// load your image
QImage img(QString("..."));
// morph it into a grayscale image
img = img.alphaChannel();
// the new color we want the logo to have
QColor foreground = label->palette().foreground().color();
// now replace the colors in the image
for(int i = 0; i < img.colorCount(); ++i) {
foreground.setAlpha(qGray(img.color(i)));
img.setColor(i, foreground.rgba());
}
// display the new logo
label->setPixmap(QPixmap::fromImage(img));
label->show();