[英]Qt- Change opacity of QPixmap
How to change opacity of QPixmap? 如何改变QPixmap的不透明度?
I've set an image as background actually I want to change its opacity, Here is my code: 我将图像设置为背景实际上我想改变它的不透明度,这是我的代码:
Call.h: Call.h:
private:
QPixmap m_avatar;
Call.cpp: 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. 我已经更改了resizeEvent函数,但它不会改变背景的不透明度。
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. 您没有使用本地
QPainter
对象。 According to QWidget Events : 根据QWidget事件 :
paintEvent()
is called whenever the widget needs to be repainted.每当需要重新绘制窗口小部件时,都会调用
paintEvent()
。 Every widget displaying custom content must implement it.每个显示自定义内容的小部件都必须实现 Painting using a
QPainter
can only take place in apaintEvent()
or a function called by apaintEvent()
.使用油漆
QPainter
只能发生在paintEvent()
或一个被调用函数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 在pixmap案例上更新paiting
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()
. 如果只需要它与使用像素图的一些不透明绘制
QPainter
,不透明度必须后才设置QPainter
活化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): 因此,在更改顺序后,pixmap
result_avatar
有两个图像(一个用不透明度1调整大小,原始像素图在顶部,不透明度为0.5):
QPainter painter;
painter.begin(&result_avatar);
painter.setOpacity(0.5);
painter.drawPixmap(0, 0, m_avatar);
painter.end()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.