使用drawBackground在QGraphicsView上绘制背景

use*_*679 4 qt background pyqt qgraphicsview pyside

我在尝试绘画和绘图时遇到问题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_()
Run Code Online (Sandbox Code Playgroud)

Ui_dialog 只是一个从 QDesigner 生成的标准对话框,其中包含名为“view”的 QGraphicsView 成员。

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

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

Tri*_*ion 5

setBackground的方法不会QPainter填充背景,而只是为绘制不透明文本、点画线和位图等操作指定背景(请参阅文档)。

您可以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_()
Run Code Online (Sandbox Code Playgroud)

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

结果:

在此输入图像描述

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