Painting background on QGraphicsView using drawBackground

泪湿孤枕 提交于 2019-12-01 00:19:41

The setBackground method of the QPainter does not fill the background but only specifies the background for operations like drawing opaque text, stippled lines and bitmaps (see the documentation).

You can use fillRect instead to first fill a rectangle of the size of your paintable area with the brush you specified.

Example:

import sys
from PyQt5 import QtCore, QtWidgets, QtGui

class myView(QtWidgets.QGraphicsView):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def drawBackground(self, painter, rect):

        background_brush = QtGui.QBrush( QtGui.QColor(255,170,255), QtCore.Qt.SolidPattern)
        painter.fillRect(rect, background_brush)

        pen = QtGui.QPen(QtGui.QColor(46, 84, 255))
        pen.setWidth(5)
        painter.setPen(pen)

        line1 = QtCore.QLineF(0,0,0,100)
        line2 = QtCore.QLineF(0,100,100,100)
        line3 = QtCore.QLineF(100,100,100,0)
        line4 = QtCore.QLineF(100,0,0,0)
        painter.drawLines([line1, line2, line3, line4])

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    scene = QtWidgets.QGraphicsScene()
    scene.addEllipse(0,0,100,100)

    view = myView(scene)
    view.show()
    view.centerOn(50,50)

    app.exec_()

It uses PyQt5 but is fairly straightforward to understand.

Result:

shows the nice magenta color you specified.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!