如何使QWidget alpha透明

时间:2011-08-06 12:30:39

标签: qt background shadow qwidget alpha-transparency

我需要创建一个alpha透明小部件,它基本上是一个带阴影的导航栏,下面的小部件需要通过阴影部分可见。小部件加载PNG,然后在paint事件上绘制它。问题是阴影全是黑色而且不是透明的。

这是我目前正在使用的代码:

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 个答案:

答案 0 :(得分:1)

你做了太多工作: - )

无需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));
}    

如果您不希望图案垂直重复,请调整高度参数。

答案 1 :(得分: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();
}
相关问题