Transparent QWidget/QScrollArea background style setting has no effect

Sebastian Roth picture Sebastian Roth · Jan 28, 2011 · Viewed 18.8k times · Source

This question relates to

I'm asking in here because I believe the SO community might have a way to fix this behavior.

So I like to set the background color of a ScrollArea to either being transparent or to a custom background image as it will contain some banners. I got it running in the Qt Creator (Designer) already! :-):

Qt Creator sample

But when deploying the app to the simulator it won't work, the are stays gray, dark gray:

Emulator sample

Here is my layout tree:

Layout Tree

And here is the stylesheet I'm using (attached & set to the MainWindow):

QMainWindow {
    background: transparent url(:/ui/designs/images_from_android/bg_plain_empty.png) top left;
}
QWidget#centralWidget {
    background-color: transparent;
}
QPushButton {
    color: red;
    border: 1px solid green;
}
QFrame#top_header {
    background: transparent url(:/ui/designs/images_from_android/bg_title_bar_landscape.png) top left repeat-x;
}
QWidget#top_banner_scroll1,
QWidget#top_banner_scroll2 {
    background: transparent url(:/ui/designs/images_from_android/stripe_bg.png) top left repeat-x;
}

This is quite puzzling. And as Qt Designer is showing me the proper design...

Answer

Johannes Matokic picture Johannes Matokic · May 10, 2013

Use the stylesheet

QScrollArea { background: transparent; }
QScrollArea > QWidget > QWidget { background: transparent; }
QScrollArea > QWidget > QScrollBar { background: palette(base); }

To understand this lets asume a similar but simplyfied layout:

scrollarea            QScrollArea
  + scrollareaContent QWidget
      + label         QLabel

Interestingly there are two widgets with an non-transparent background. The first is the scrollarea itself (made transparent with the first line of the stylesheet).

The other one (which I didn't expect) is scrollareaContent which gets addressed with the second line. There the first QWidget is the private viewport of the QScrollArea which could not be accessed directly. The other one is the scrollareaContent. This approach should make all QScrollAreas transparent without affecting any of the other widgets.

UPDATE: I added a third line to the stylesheet which prevents the scrollbars from becoming transparent as they are also QWidgets two levels below QScrollArea.