How can I create transparent labels and buttons where the window's background pixmap shines through the label?

The label will be transparent by default, so the background pixmap of the parent will shine through the label. For the buttons you need to fill the QPalette::Button [doc.qt.nokia.com] color role to have no brush. Note that changing the palette will not work for all styles, it will for example not work for the XP and MacStyle which are pixmap based. For these styles you will have to draw this yourself in the paintEvent() [doc.qt.nokia.com] or set a style that supports this on the button.

See the following example:

  1. #include <QtGui>
  2.  
  3. int main(int argc, char **argv)
  4. {
  5.   QApplication app(argc, argv);
  6.   QPixmap pixmap(200, 200);
  7.   {
  8.     QPainter p(&pixmap);
  9.     p.fillRect(0, 0, 200, 200, QRadialGradient(100, 100, 100, 150, 150));
  10.   }
  11.   QWidget parent;
  12.   QPalette ppal = parent.palette();
  13.   ppal.setBrush(parent.backgroundRole(), pixmap);
  14.   parent.setPalette(ppal);
  15.  
  16.   QWidget *wid = new QWidget(&parent);
  17.   QLabel *label = new QLabel("Testing 1, 2, 3, 4, 5, 6, 7, 8, ....", wid);
  18.   QPushButton *button = new QPushButton(wid);
  19.   button->setText("Button");
  20.   button->setAutoFillBackground(false);
  21.   QPalette pal = button->palette();
  22.   pal.setBrush(QPalette::Button, Qt::NoBrush);
  23.   button->setPalette(pal);
  24.  
  25.   QVBoxLayout *layout = new QVBoxLayout(wid);
  26.   layout->addWidget(label);
  27.   layout->addWidget(button);
  28.   label->setFont(QFont("Arial", 30));
  29.  
  30.   parent.show();
  31.   parent.resize(300, 200);
  32.   int ret = app.exec();
  33.   return ret;
  34. }
  35.  

No comments

Write a comment

Sorry, you must be logged in to post a comment.