Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 869
Managu Avatar asked Jun 18 '12 01:06

Managu


1 Answers

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.

like image 88
Arnold Spence Avatar answered Nov 04 '22 11:11

Arnold Spence