Search code examples
c++windowsqtqpixmap

How can I create a translucent copy of a QPixmap?


In the program I'm making, I need two images, which are exactly the same but one is translucent. For performance reasons, I want to create two separate QPixmaps instead of using just one and setting the opacity of a QPainter. Is there a straightforward way to do this?


Solution

  • No, there is no performant way to do this.

    To modify channels of a QPixmap it must be: Converted into a QImage, modified, converted back to a QPixmap. Depending upon your application the round trip will probably make it simpler to just do this in the QPainter: http://www.qtcentre.org/threads/51158-setting-QPixmap-s-alpha-channel

    However if you could do roll this into your startup time the round trip may be reasonable, preventing repeated conversions in QPainter.

    1. Convert your QPixmap to a QImage:http://doc.qt.io/qt-5/qpixmap.html#toImage
    2. If you didn't have an alpha channel in your QPixmap you'll need to add one: http://doc.qt.io/qt-5/qimage.html#convertToFormat
    3. Then for each pixel in your image call setPixel: http://doc.qt.io/qt-5/qimage.html#pixel-manipulation (Note that setPixel takes a QRgb. You'll need to get the red, green, and blue channels from the pixel to be modified and use these along with your desired alpha value in qRgba: http://doc.qt.io/qt-5/qcolor.html#qRgba)
    4. Finally you'll need to use convertFromImage: http://doc.qt.io/qt-5/qpixmap.html#convertFromImage