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 solid blue rectangle, instead of the semi-transparent one I expect due to giving the QBrush
an alpha value.
I've also tried drawing to an intermediate QImage
or QPixMap
, playing around with painter.setCompositionMode(...)
. No luck so far.
Thus my question: How can I convince Qt to draw a semi-transparent rectangle to my PageView
?
EDIT: If it's relevant, I'm building this under Qt 4.8.1 on Windows.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With