Search code examples
pythonqtpyqtpyqt4qtstylesheets

Stylesheet for nested custom widget not applied


I expect the following code to show a small black area inside outer main window:

class Canvas(QWidget):
    pass

app = QApplication(sys.argv)
outer = QWidget()
w = Canvas(outer)
w.setStyleSheet("background-color: black")
outer.show()

But looks like the stylesheet is not applied: entire outer window is gray. However, if w is a QWidget, code works as expected. When Canvas instance is shown directly (without parent) stylesheet is properly applied as well:

w = Canvas()
w.setStyleSheet("background-color: black")
w.show()

This code shows a black window. I have tried same in C++ with Qt 4.8.6 and stylesheet is also properly applied for nested widgets derived from QWidget.

What am I missing? I am using python 2.7.6, Qt 4.8.6 and PyQt 4.10.4 under Ubuntu 14.04.


Solution

  • A QWidget subclass will ignore stylesheets by default (for performance reasons).

    Try this:

    w = Canvas(outer)
    w.setAttribute(QtCore.Qt.WA_StyledBackground)
    w.setStyleSheet("background-color: black")