Important: Please read the Qt Code of Conduct -

convert QPixmap to QImage without loosing alphaChannel

  • Hi,

    i have a QPixmap that has an alpha channel.
    now i want to change some pixels and therefore convert it into a QImage

    QImage image(pixmap.toImage().convertToFormat(QImage::Format_ARGB32));

    When i now iterate over the pixels, the alpha value is always 255.
    How can i prevent loosing the alpha channel?

  • Lifetime Qt Champion

    @gde23 "Usually this will be QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha" from
    Maybe you should try QImage::Format_ARGB32_Premultiplied ?

  • @jsulm I have tried

    QImage image(pixmap.toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied));

    However still the same problem.
    I think also the order does not make sense since first it is converted to image (I guess here the alpha gets lost) and then afterwards it is converted to different format?

  • Lifetime Qt Champion

    @gde23 Try

    QImage image = pixmap.toImage();

  • @jsulm still the same result.

    or maybe the problem is with convertig to QColor?
    Here is the complete function.

    void grayOut(QPixmap& pixmap)
        QImage image = pixmap.toImage();
        for(int x=0; x<image.width(); x++)
            for(int y=0; y<image.height(); y++)
                QColor colour(image.pixel(x,y));
                int m = +;
                int alpha = colour.alpha();
                colour.setRgb(m, m, m, alpha);
                image.setPixel(x, y, colour.rgba());
        pixmap = QPixmap::fromImage(image);

    all i am trying todo is to gray out the icon, however

    int alpha = colour.alpha();

    always returns 255

  • I finally have a solution:

    QIcon can do it

    QPixmap TreeModelWrapper::grayOut(const QPixmap& pixmap) const
        QIcon icon(pixmap);
        QSize size(16,16);
        return icon.pixmap(size, QIcon::Disabled);

Log in to reply