How to make QImage or QPixmap translucent - or why is setAlphaChannel deprecated?

4.7 and like to overlay two images on qgraphicsview. The image above must be translucent so that you can see it. Initially, both images are completely opaque. I was expecting some function to set a global alpha value for each pixel, but it looks like there is no such function. The closest to this is QPixmap :: setAlphaChannel (const QPixmap and alphaChannel), which, however, is marked as deprecated with Qt-4.6. Instead, the manual references CompositionModes QPainter, but I am unable to add transparency to the opaque image as I want. Can someone point me to a working example or share some code?

Edit: I am almost sorry that I have my own answer, and now a few hours after the question. From this article, I realized that the following code does the job. I'm just wondering if this is considered “better” (which often translates faster) than changing alpha values ​​in pixels.

QPainter p; 
p.begin(image);
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.fillRect(image->rect(), QColor(0, 0, 0, 120));
p.end();            
mpGraphicsView->scene()->addPixmap(QPixmap::fromImage(image->mirrored(false,true),0));  
+5
source share
3 answers

The demo version of Qt lineup can be a little intimidating because they are trying to show everything. Hopefully the demo and QPainter documentation will be useful to you. You want to use CompositionMode :: SourceOver and make sure that the images are converted to ARGB32 (pre-multiplied). From the documentation:

When the paint device is a QImage, the image format must be set to Format_ARGB32Premultiplied or Format_ARGB32 for the composition modes to have any effect. For performance the premultiplied version is the preferred format.

+6

.

void ClassName::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setOpacity(1.00);  //0.00 = 0%, 1.00 = 100% opacity.
    painter.drawPixmap(QPixmap(path));
}
+6

, QImage QPixmap, QPixmap . , QPixmaps , . pixmap X- GL-. , QPixmap QImage , .

, , - , , blitting. , , , :

for (int y = 0; y < image.height() ++y) {
  QRgb *row = (QRgb*)image.scanLine(y);
  for (int x = 0; x < image.width(); ++x) {
    ((unsigned char*)&row[x])[3] = alpha;
  }
}

: QImage, painter.drawImage(), -.

+2
source

All Articles