[Qt-interest] Applying background image to QMainWindow?

John Posner jjposner at optimum.net
Sun Dec 27 18:26:36 CET 2009


Mike Polan wrote:
> Hi all,
>
> I'm using the latest Qt on Mac OS X, and I'm a bit stuck on trying to 
> set an image as the background for a QMainWindow. What I'm looking 
> for, is to somehow set such an image as a background of my program's 
> main window, and also to let all child widgets (specifically 
> containers like QGroupBox) have transparent backgrounds so the image 
> shows through. I tried setting the main window's CSS properties like so:
>
> // inside mainwindow.cpp -> class derives from QMainWindow
> setStyleSheet("background-image: url(some_bg.png)");
>
> This seems to work, but the problem is that EVERY child widget also 
> tries to display that background. That is, instead of having one, 
> uniform background image in the main window, I get several partial 
> ones displayed on each widget's background. How would I go about 
> achieving the aforementioned result?

The following worked for me (although it mixes stylesheets and palettes, 
which the Qt documentation warns against).

 * Use a QGraphicsView with a stylesheet-specified background image.
 * Create a QGroupBox with a palette-specified transparent background.
 * Embed the QGroupBox in a QGraphicsProxyWidget.

Here's the proof-of-concept Python code:

#-------------------------
from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication([])
win = QMainWindow()

# create a view and scene
view = QGraphicsView()
view.setStyleSheet("background-image: url(apple-red.png);")
win.setCentralWidget(view)
scene = QGraphicsScene()
view.setScene(scene)

# create a group-box
grp = QGroupBox("My Group")
grp.setLayout(QVBoxLayout())
grp.layout().addWidget(QRadioButton("aaa"))
grp.layout().addWidget(QRadioButton("bbb"))

# make the group-box transparent
pal = QPalette()
pal.setColor(QPalette.Background, Qt.transparent)
grp.setPalette(pal)

# embed the group-box in a proxy, and add to scene
pA = QGraphicsProxyWidget()
pA.setWidget(grp)
scene.addItem(pA)

# go
win.show()
app.exec_()
#-------------------------


HTH,
John




More information about the Qt-interest-old mailing list