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_())