如何使QImage或QPixmap半透明 - 或者为什么setAlphaChannel已过时?

FFo*_*Fox 7 transparency qt4 qpainter qimage

4.7并且喜欢在qgraphicsview上叠加两个图像.顶部的图像应是半透明的,以便透视它.最初两个图像都是完全不透明的.我期望一些功能可以为每个像素设置一个全局alpha值,但似乎没有这样的功能.最接近它的是QPixmap :: setAlphaChannel(const QPixmap&alphaChannel),但是,自Qt-4.6起,它被标记为过时.相反,手册指的是QPainter的CompositionModes,但我没有成功为我想要的不透明图像添加透明度.有人能指出我的工作实例或分享一些代码吗?

编辑: 我很抱歉有一个自己的答案,现在问了几个小时后.从这篇文章中我发现以下代码完成了这项工作.我只是想知道这是否被认为是"更好"(通常转化为更快)比按像素方式修改alpha值.

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));  
Run Code Online (Sandbox Code Playgroud)

bjo*_*rnz 8

Qt的组成演示可有点吓人,因为他们试图证明一切了.希望演示和QPainter文档对您有所帮助.您想使用CompositionMode :: SourceOver并确保将图像转换为ARGB32(预乘).从文档:

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.


小智 8

使用您的画家对象并设置不透明度.

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