0

Observe the following code

#!/usr/bin/env python3
from PyQt5 import QtWidgets as w


class MyWidget(w.QWidget): pass


app = w.QApplication([])
frame = w.QWidget()
grid = w.QGridLayout()
frame.setLayout(grid)

w1 = MyWidget()
w2 = w.QWidget()

grid.addWidget(w1)
grid.addWidget(w2)

w1.setStyleSheet("background-color: red")
w2.setStyleSheet("background-color: red")

frame.show()
app.exec_()

The resulting app doesn't produce two identical red widgets. Qt documentation implies that things like stylesheets should work just perfectly with subclassed widgets. What's wrong here?

an empty space and red box where should be two red boxes

mike3996
  • 17,047
  • 9
  • 64
  • 80

1 Answers1

1

As they comment in this post and this post so that the inheriting classes you must overwrite paintEvent():

#!/usr/bin/env python3
from PyQt5 import QtGui, QtWidgets


class MyWidget(QtWidgets.QWidget):
    def paintEvent(self, event):
        opt = QtWidgets.QStyleOption()
        opt.initFrom(self)
        p = QtGui.QPainter(self)
        self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, p, self)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    frame = QtWidgets.QWidget()
    grid = QtWidgets.QGridLayout(frame)

    for w in (MyWidget(), QtWidgets.QWidget()):
        grid.addWidget(w)
        w.setStyleSheet("background-color: red")

    frame.resize(640, 480)
    frame.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241