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

时间:2018-11-15 18:30:47

标签: 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.addWidget(w2)

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

frame.show()
app.exec_()

生成的应用程序不会产生两个相同的红色小部件。 Qt文档暗示样式表之类的东西应该与子类化的窗口小部件完美配合。怎么了?

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

1 个答案:

答案 0 :(得分:1)

当他们在this postthis post中进行注释时,继承类必须覆盖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_())