The Problem
The classic situation that this problem can occur is when one wants to create a QPixmap with a transparent background and then draws on only some of the available pixels. This process is akin to creating a transparent GIF. Well there is a wrong way and a right way. I discovered this because I was using the wrong way and was getting away with it as long as I was writing to every pixel. Then there was a case when I was not writing to all pixels and the QPixmap unwritten to pixels (i.e., the background) was not transparent as I expected. Here is the wrong way.
The Wrong Way
1 2 3 4 5 6 7 | QPixmap *pix = new QPixmap(Size()); QPainter painter; painter.begin(pix); painter.fillRect(0,0,pix->width(),pix->height(),QBrush(QColor(0,0,0,0))); painter.drawPixmap(pix->rect(),*m_image); painter.end(); |
The problem is that line 4 does not fill the QPixmap with anything as the alpha is set to 0. Think of fill with alpha as a merge operation and not a replace. I was thinking of it as a replace and therefore I was replacing every pixel with a fully transparent black. However, because fillRect is really a merge I was merging a transparent pixel with the background effectively doing nothing.
The correct way is as follows:
The Right Way
1 2 3 4 5 6 7 | QPixmap *pix = new QPixmap(Size()); pix->fill(Qt::transparent); QPainter painter; painter.begin(pix); painter.drawPixmap(pix->;rect(),*m_baseSymbol); painter.end(); |
Notice that line 2 is new and this fill command is a replace fill.
Summary
In summary QPixmap fill(…) command is a replace fill; whereas, QPainter fillRect(…) is a merge fill. I hope this help clarity the nature of these two operations.