C++ 如何在 Qt 中绘制半透​​明矩形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11076011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:49:02  来源:igfitidea点击:

How do I draw a semi-transparent rectangle in Qt?

c++qtuser-interface

提问by Managu

I'm trying to draw a semi-transparent rectangle on top of an image to act as a highlight. Unfortunately, nothing I try seems to be able to perform the transparency effect I want. Instead I just get solid filled rectangles, with no transparency.

我正在尝试在图像顶部绘制一个半透明矩形作为高光。不幸的是,我尝试的任何东西似乎都无法实现我想要的透明效果。相反,我只是得到实心填充的矩形,没有透明度。

Here's what I'm doing right now:

这是我现在正在做的事情:

void PageView::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QImage img=...;

    painter.drawImage(0, 0, img);
    ...
    // draw a light blue, transparent rectangle to highlight
    QRect rect=...;
    painter.fillRect(rect, QColor(128, 128, 255, 128));
    ...
}

Unfortunately, for me, this draws a solidblue rectangle, instead of the semi-transparent one I expect due to giving the QBrushan alpha value.

不幸的是,对我来说,这绘制了一个蓝色矩形,而不是我期望的半透明矩形,因为它给出了QBrush一个 alpha 值。

I've also tried drawing to an intermediate QImageor QPixMap, playing around with painter.setCompositionMode(...). No luck so far.

我还尝试绘制到中间QImageQPixMap,玩弄painter.setCompositionMode(...). 到目前为止没有运气。

Thus my question: How can I convince Qt to draw a semi-transparent rectangle to my PageView?

因此我的问题是:如何说服 Qt 为我的PageView.

EDIT: If it's relevant, I'm building this under Qt 4.8.1 on Windows.

编辑:如果相关,我将在 Windows 上的 Qt 4.8.1 下构建它。

回答by Arnold Spence

The code works for me with a slight modification as it does not compile as you have it:

代码对我有用,稍加修改,因为它不会像你那样编译:

painter.fillRect(rect, QBrush(QColor(128, 128, 255, 128)));

NOTE:

笔记:

The OP was painting the semi transparent rectangle in a loop causing the same area to be painted multiple times. This will result in an additive effect which will eventually cause that area to look the same as a solid fill.

OP 在循环中绘制半透​​明矩形,导致多次绘制同一区域。这将导致附加效果,最终导致该区域看起来与实体填充相同。