4

我需要创建一个 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();
    }
}

有人知道我需要更改什么以确保小部件真正透明吗?

4

2 回答 2

1

你做的工作太多了:-)

The setAttribute call is not necessary. By default, a widget will not draw anything on its background (assuming Qt >= 4.1). Calling QWidget::paintEvent is also unnecessary - you don't want it to do anything.

Rather than doing the pattern fill yourself, let Qt do it with a 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));
}    

Adjust the height parameter if you don't want the pattern to repeat vertically.

于 2011-08-06T13:17:32.757 回答
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();
}
于 2011-08-06T13:14:46.367 回答