1

My code generates a Window containing two QWidgets, a red (wg1) and a blue (wg2) one. If they become Fields (commented out) which inherits from QWidget, their color disappears.

My question is: Why is it necessary for a Field (which inherits from QWidget), to have the line

self.setAttribute(Qt.WA_StyledBackground, True)

in its __init__-method while a QWidget doesn't need this line?

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout
from PyQt5.QtCore import Qt

class Field(QWidget):
    def __init__(self, name):
        super().__init__()
        self.name = name
        # self.setAttribute(Qt.WA_StyledBackground, True)# !!!
        
    def mousePressEvent(self, event):
        print(f" click makes {self.name} green")
        self.setStyleSheet("background: #00ff00;")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    root = QWidget()
    grid = QGridLayout()
    root.setLayout(grid)
    root.resize(300,100)

    wg1 = QWidget()
    wg2 = QWidget()
    # wg1 = Field('wg1')
    # wg2 = Field('wg2')

    wg1.setStyleSheet("background: #aa1111;")
    grid.addWidget(wg1, 0, 0)

    wg2.setStyleSheet("background: #1111aa;")
    grid.addWidget(wg2, 0, 2)

    root.show()
    sys.exit(app.exec_())
ewi
  • 175
  • 1
  • 9

1 Answers1

1

The explanation resides in the section related to QWidget of the stylesheet reference:

If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:

By default, QWidget does that by default, but QWidget subclasses do not, so you either set the flag or you implement the paintEvent.

In any case, consider using stylesheet selectors and avoid generic/universal syntax as they often result in unexpected behavior for complex child widgets.

musicamante
  • 41,230
  • 6
  • 33
  • 58