How to make QWidget alpha transparent

I need to create an alpha transparent widget, basically it is a navigation bar with a shadow, and the widgets below should be partially visible through the shadow. The widget loads the PNG, and then draws it on the drawing event. The problem is that the shadow is all black and not alpha transparent.

This is the code I'm currently using:

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 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(); } } 

Does anyone know what I need to change to make sure the widget is really transparent?

+4
source share
2 answers

You do too much work :-)

A call to setAttribute not required. By default, the widget will not draw anything against its background (assuming Qt> = 4.1). The call to QWidget::paintEvent also not needed - you do not want to do anything.

Instead of making a template, populate Qt by doing this with 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 do not want the pattern to repeat vertically.

+1
source

Are you sure your PNG file is actually transparent? The following (which is essentially what you are doing) works for me. If this fails on your computer, perhaps indicate which version of Qt you are using and which platform.

 #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(); } 
0
source

All Articles