Python 为什么我继承的小部件的行为不像超类

Python 为什么我继承的小部件的行为不像超类,python,pyqt,pyqt5,Python,Pyqt,Pyqt5,请遵守以下代码 #!/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.a

请遵守以下代码

#!/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_()
生成的应用程序不会生成两个相同的红色小部件。Qt文档意味着样式表之类的东西应该与子类小部件完美配合。这里怎么了

当它们在和中注释时,您必须覆盖继承类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_())