Rendering QWidget to QImage loses alpha-channel
Asked Answered
C

1

4

I have a simple Qt widget. It's a QLabel with a simple CSS style applied. The important part of the style is a round border:

QString css("border-style: solid;"
       "border-width: 3px;"
       "border-radius: 7px;");

It is displayed on screen fine. The corners of the label beyond the border are filled with transparent color, so it looks great on any background. Here's how it looks when displayed over another widget (which has dark grey background color):

enter image description here

Now, when I render it to QImage like so

QImage bitmap(label->size(), QImage::Format_ARGB32);
QPainter painter(&bitmap);
balloon->render(&painter);
bitmap.save("C:/1.png");

I get this (image opened in image editor to demonstrate a problem clearly):

enter image description here

Note how transparency is not preserved around the corners. What's the problem? How can I render it correctly?

P. S. I have tried this to test that QImage is capable of saving alpha channel, and that my image editor displays it correctly:

bitmap.fill(QColor::fromRgba(qRgba(0, 0, 0, 0)));
bitmap.save("C:/1.png");

It works fine, I can see transparency as checkered pattern.

Claudetteclaudia answered 2/12, 2013 at 9:5 Comment(0)
C
6

This does the trick:

QImage bitmap(label->size(), QImage::Format_ARGB32);
bitmap.fill(Qt::transparent);
QPainter painter(&bitmap);
label->render(&painter, QPoint(), QRegion(), QWidget::DrawChildren);
Claudetteclaudia answered 2/12, 2013 at 10:14 Comment(4)
cause is that the default color of image isn't Qt::transparentWood
@ratchetfreak: it's not just that. Simply calling fill is not enough, QWidget::DrawChildren is also neccessary.Claudetteclaudia
Very late to the party, but I ran into this type of scenario just today. It's not really about DrawChildren. The default render flags are DrawWindowBackground | DrawChildren. By specifying only DrawChildren, you lose the DrawWindowBackground flag, which is what you need here.Ronald
@KilianBrendel, I see! Great find, and thanks for taking the time to post the explanation.Claudetteclaudia

© 2022 - 2024 — McMap. All rights reserved.