PDA

View Full Version : Changing Opacity in Qlabel



desch
3rd December 2007, 11:15
Hi Everybody,

I try to change the opacity in QLabel.
Using the paintEvent with this kind of code:


void myLabel::paintEvent(QPaintEvent * e)
{

QPainter p(this);

// if pixmap
if (! pixmap()->isNull())
p.drawPixmap(pixmap()->rect(), * pixmap());

p.setOpacity(0.5);

// if Text
if (! text().isEmpty())
p.drawText(rect(), text());

}

The aim is just to change the opacity level ; The problem with this code is that , I have to redraw everything manually : style , pixmap position, text position...
it's not so easy...

If someone has something more easy, it will be fine

Thanks to all

David

marcel
3rd December 2007, 11:38
You can call the base class paintEvent in your paint event and then just draw all additional stuff.

desch
3rd December 2007, 12:00
But the problem is :

opacity required :Qpainter

On my label I apply a style sheet, a pixmap, and sometimes a text.

When I do
QPainter p(this); eveything must be redraw

and I don't know How to change the opacity with the class QPaintEvent()

Thanks

David

jpn
3rd December 2007, 12:29
For a transparent pixmap, apply the opacity to the pixmap:



QPixmap original = ...;

QPixmap result(original.size());
result.fill(Qt::transparent);
QPainter painter;
painter.setOpacity(0.5);
painter.begin(&result);
painter.drawPixmap(0, 0, original);
painter.end();

label->setPixmap(result);


For transparent text, adjust palette:


QPalette palette = label->palette();
QColor color = palette.color(QPalette::Text);
color.setAlpha(127);
palette.setColor(QPalette::Text, color);
label->setPalette(palette);

or use style sheets:


QLabel { color: rgba(0, 0, 0, 50%) }

No reimplementing of paintEvent() needed. :)

desch
3rd December 2007, 14:29
I 've tested your exmaple but its didn't work

This is what I've done in a subclass of a label:



void myLabel::setPixmap(const QPixmap & pix)
{

QPixmap result(pix);
result.fill(Qt::transparent);

QPainter painter;
painter.setOpacity(0.5);
painter.begin(&result);
painter.drawPixmap(0, 0, result);
painter.end();

QLabel::setPixmap(result);

}

May I do something wrong ; the pixmap is not visible for me

Thanks

desch
3rd December 2007, 15:13
after many test : I found my (stupid) problem

the good code on a subclass of QLabel:


QPixmap result(pix.size());
result.fill(Qt::transparent);

QPainter painter;
painter.begin(&result);
painter.setOpacity(0.5);
painter.drawPixmap(0, 0, pix);
painter.end();

QLabel::setPixmap(result);

opacity must be done afer the "begin"


Ok thanks to all ;)

David

jpn
3rd December 2007, 15:19
after many test : I found my (stupid) problem

opacity must be done afer the "begin"
Sorry, that's actually my bad. :)