使用 drawBackground 在 QGraphicsView 上绘制背景

Painting background on QGraphicsView using drawBackground

我在 QGraphicsView/Scene 上尝试绘画时遇到问题。我正在绘制一堆 QLineF as background overridingQGraphicsView::drawBackGround`。但是,当我尝试更改背景颜色时,没有任何反应。

下面是我正在做的最简单的例子:

import sys
import platform
import ctypes
from PySide import QtCore, QtGui
from mygv import Ui_Dialog
import sys

class myView(QtGui.QDialog):
    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.view.drawBackground = self.drawBackground
        self.ui.view.wheelEvent = self.wheelEvent
        self.scene = QtGui.QGraphicsScene()
        self.ui.view.setScene(self.scene)
        self.scene.addEllipse(0,0,100,100)

    def drawBackground(self, painter, rect):

        bbrush = QtGui.QBrush( QtGui.QColor(255,170,255), QtCore.Qt.SolidPattern)
        painter.setBackgroundMode(QtCore.Qt.OpaqueMode)

        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.setBackground(bbrush)
        painter.drawLines([line1, line2, line3, line4])




    def wheelEvent(self,event):
        factor = 1.41 ** (event.delta() / 240.0)
        self.ui.view.scale(factor, factor)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    diag = myView()
    diag.show()
    diag.ui.view.centerOn(50,50)
    app.exec_()

Ui_dialog 只是一个从 QDesigner 生成的标准对话框,带有一个名为 "view" 的 QGraphicsView 成员。

这只是问题的一个例子。我需要能够在我的应用程序执行期间系统地更改背景颜色。

我错过了什么或(明显)做错了什么?

QPaintersetBackground方法不填充背景,仅指定用于绘制不透明文本、点画线和位图等操作的背景(参见documentation)。

您可以使用 fillRect 代替,首先用您指定的画笔填充可绘制区域大小的矩形。

示例:

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

它使用 PyQt5,但相当容易理解。

结果:

显示您指定的漂亮洋红色。