How to draw a translucent rectangle in Qt?

I am trying to draw a translucent rectangle over the image to act as a highlight. Unfortunately, nothing that I am trying to seem to be able to fulfill the transparency effect that I want. Instead, I just get solid filled rectangles, without transparency.

Here is what I am 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 blue- blue- blue rectangle instead of the translucent one that I expect because the QBrush value matches the alpha value.

I also tried drawing before the intermediate QImage or QPixMap , playing with painter.setCompositionMode(...) . So far no luck.

So my question is: how can I convince Qt to draw a translucent rectangle for my PageView ?

EDIT . If relevant, I build it under Qt 4.8.1 on Windows.

+7
source share
1 answer

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

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

Note:

The OP drew a translucent rectangle in the loop, causing the same area to draw several times. This will lead to an additive effect, which will ultimately lead to the fact that this area will look just like a solid fill.

+13
source

All Articles