如何使一个QWidget部件具有透明度

4
我需要创建一个alpha透明的小部件,它基本上是一个带有阴影的导航栏,并且下面的小部件需要通过阴影部分可见。该小部件加载PNG文件,然后在绘制事件中将其绘制出来。问题是阴影全部是黑色且不透明。
这是我目前正在使用的代码:
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();
    }
}

有人知道我需要改变什么来确保小部件真正透明吗?
2个回答

1

你做的工作太多了 :-)

setAttribute 调用是不必要的。默认情况下,小部件不会在其背景上绘制任何内容(假设 Qt >= 4.1)。调用 QWidget::paintEvent 也是不必要的 - 你不希望它做任何事情。

与其自己进行图案填充,不如使用 QBrush 让 Qt 来完成:

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 Blue Waffle:感谢您的修复!只是想提醒一下:在编辑时请不要留下编辑标记。您可以通过链接“X时间前编辑”(假设该帖子已被编辑)查看每个帖子的编辑历史记录。 - Mat

0

你确定你的PNG文件实际上是透明的吗?以下代码(基本上就是你正在做的事情)在我的机器上可以正常工作。如果在你的机器上失败了,也许需要说明你使用的Qt版本和平台。

#include <QtGui>

class TransparentWidget : public QWidget {
public:
  TransparentWidget()
    : QWidget(),
      background_pixmap_(":/semi_transparent.png") {
    setFixedSize(400, 100);
  }
protected:
  void paintEvent(QPaintEvent *) {
    QPainter painter(this);
    int x = 0;
    while (x < width()) {
      painter.drawPixmap(x, 0, background_pixmap_);
      x += background_pixmap_.width();
    }
  }
private:
  QPixmap background_pixmap_;
};

class ParentWidget : public QWidget {
public:
  ParentWidget() : QWidget() {
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(new TransparentWidget);
    layout->addWidget(new QPushButton("Button"));
    setLayout(layout);
    setBackgroundRole(QPalette::Dark);
    setAutoFillBackground(true);
  }
};

int main(int argc, char **argv) {
  QApplication app(argc, argv);
  ParentWidget w;
  w.show();
  return app.exec();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接