3

I have a transparent image (QImage) overlayed over a video in Qt. I want to change the color of the transparent image only on clicks of button. Can some one tell me how to do this?

Thank You.

Sid411
  • 703
  • 2
  • 9
  • 25

1 Answers1

11

This can be done in many ways. I suggest to use QPainter to create new image. If you set SourceIn composition mode, starting image's alpha channel will be applied to any drawing that you will do. You just need to fill image with desired color.

QPixmap source_image; // should be preserved in a class member variable
QRgb base_color; // desired image color

QPixmap new_image = source_image;
QPainter painter(&new_image);
painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
painter.fillRect(new_image.rect(), base_color);
painter.end();

ui->label->setPixmap(new_image); // showing result

Note that I use QPixmap instead of QImage because QPixmaps are more efficient to display (and possibly paint). If you for some reason still want to use QImage, this code will work with QImage without any changes (excluding the last line of course).

Source image: source image        Result: result

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • I tried this method. It is saying cannot paint on an image with the QImage::Format_Indexed8 format. Is it because it is a png transparent image. – Sid411 Mar 04 '14 at 05:10
  • I tried using image->setColor since it is a format8 image. In this case it paints even the area which is transparent. I want only the non transparent part to take a color. Thank You – Sid411 Mar 04 '14 at 05:58
  • 1
    Indexed8 format is not necessary for transparency. ARGB32 format is commonly used. Use `source_image = source_image.convertToFormat(QImage::Format_ARGB32);` to convert image to paintable format. – Pavel Strakhov Mar 04 '14 at 13:33
  • Doesn't work at least on Qt 5.3.1, 32 bit on OS X, or may I am doing something wrong. I am trying with QImage only instead of QPixmap, since I need to use `source_image.convertToFormat(QImage::Format_ARGB32);`. In place of `base_color` I used `painter.fillRect(new_image.rect(), QColor("red");` . I am getting a blank label. – SexyBeast Feb 14 '16 at 13:39