简体   繁体   中英

Qt- Change opacity of QPixmap

How to change opacity of QPixmap?

I've set an image as background actually I want to change its opacity, Here is my code:

Call.h:

private:
    QPixmap m_avatar;

Call.cpp:

void Call::resizeEvent(QResizeEvent *e)
{
    QPalette pal = palette();
    pal.setBrush(backgroundRole(), m_avatar.scaled(e->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
    setPalette(pal);
}

I've changed resizeEvent function, but it doesn't change background's opacity.

void Call::resizeEvent(QResizeEvent *e)
{
    QPixmap result_avatar(m_avatar.size());
    result_avatar.fill(Qt::transparent);
    QPainter painter;
    painter.setOpacity(0.5);
    painter.begin(&result_avatar);
    painter.drawPixmap(0, 0, m_avatar);
    painter.end();
    QPalette pal = palette();
    pal.setBrush(backgroundRole(), result_avatar.scaled(e->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
    setPalette(pal);
}

Any suggestion?

You are not using local QPainter object. According to QWidget Events :

paintEvent() is called whenever the widget needs to be repainted. Every widget displaying custom content must implement it. Painting using a QPainter can only take place in a paintEvent() or a function called by a paintEvent() .

Here it works:

void Call::paintEvent(QPaintEvent *)
{
    // create a new object scaled to widget size
    QPixmap result_avatar = m_avatar.scaled(size());

    QPainter painter(this);
    painter.setOpacity(0.5);
    // use scaled image or if needed not scaled m_avatar
    painter.drawPixmap(0, 0, result_avatar);
}

Update for paiting on pixmap case

If it is needed only to paint with some opacity on a pixmap using QPainter , the opacity must be set only after QPainter activation by QPainter::begin() . So, after changing the order the pixmap result_avatar has two images (one resized with opacity 1 and original pixmap on top with opacity 0.5):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM