我需要创建一个 alpha 透明小部件,它基本上是一个带有阴影的导航栏,下面的小部件需要通过阴影部分可见。小部件加载一个 PNG,然后在绘制事件上绘制它。问题是阴影是全黑的,不是 alpha 透明的。
这是我目前使用的代码:
NavigationBar::NavigationBar(QWidget *parent) : XQWidget(parent) {
backgroundPixmap_ = new QPixmap();
backgroundPixmap_->load(FilePaths::skinFile("NavigationBarBackground.png"), "png");
setAttribute(Qt::WA_NoBackground, true); // This is supposed to remove the background but there's still a (black) background
}
void NavigationBar::paintEvent(QPaintEvent* event) {
QWidget::paintEvent(event);
QPainter painter(this);
int x = 0;
while (x < width()) {
painter.drawPixmap(x, 0, backgroundPixmap_->width(), backgroundPixmap_->height(), *backgroundPixmap_);
x += backgroundPixmap_->width();
}
}
有人知道我需要更改什么以确保小部件真的透明吗?
最佳答案
你做的工作太多了:-)setAttribute
没有必要打电话。默认情况下,小部件不会在其背景上绘制任何内容(假设 Qt >= 4.1)。调用 QWidget::paintEvent
也是不必要的 - 你不希望它做任何事情。
与其自己做模式填充,不如让 Qt 用 QBrush
来做。 :
NavigationBar::NavigationBar(QWidget *parent) : XQWidget(parent) {
backgroundPixmap_ = new QPixmap();
backgroundPixmap_->load(FilePaths::skinFile("NavigationBarBackground.png"), "png");
// debug check here:
if (!backgroundPixmap_->hasAlphaChannel()) {
// won't work
}
}
void NavigationBar::paintEvent(QPaintEvent* event) {
QPainter painter(this);
painter.fillRect(0, 0, width(), height(), QBrush(*backgroundPixmap));
}
如果您不希望图案垂直重复,请调整高度参数。
关于qt - 如何使 QWidget alpha 透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6966784/