Python 在QtCore.Qt.CrossPattern上设置图案颜色和线条厚度

Python 在QtCore.Qt.CrossPattern上设置图案颜色和线条厚度,python,qt,pyqt,qgraphicsview,brush,Python,Qt,Pyqt,Qgraphicsview,Brush,我在我的QtGui.QGraphicsView的init中使用了以下内容来创建一个漂亮的网格/交叉模式。但不确定如何更改交叉图案线的背景色或厚度?使用setColor设置颜色,但这只会更改交叉图案的颜色,而不会更改背景 有没有办法改变这些,或者我应该使用不同类型的风格 import PySide.QtGui as QtGui import PySide.QtCore as QtCore class NodeGraphView(QtGui.QGraphicsView): def __i

我在我的
QtGui.QGraphicsView
的init中使用了以下内容来创建一个漂亮的网格/交叉模式。但不确定如何更改交叉图案线的背景色或厚度?使用
setColor
设置颜色,但这只会更改交叉图案的颜色,而不会更改背景

有没有办法改变这些,或者我应该使用不同类型的风格

import PySide.QtGui as QtGui
import PySide.QtCore as QtCore

class NodeGraphView(QtGui.QGraphicsView):

    def __init__(self, parent):
        super(NodeGraphView, self).__init__(parent)

        self.fg_brush = QtGui.QBrush()
        self.fg_brush.setStyle(QtCore.Qt.CrossPattern)
        self.fg_brush.setColor(QtGui.QColor(42, 42, 42, 255))

        self.setBackgroundBrush(self.fg_brush)

视图背景基本上只用于“填充”;交叉图案非常基本且不可配置(颜色除外,因为这是基本填充属性)。但绘制自己的网格并不困难,这样您就有了更多的控制(例如厚度、虚线/虚线、显示原点等):

  • 为网格线创建笔:为其指定颜色和宽度
  • 您可以将笔设置为具有恒定的“装饰”宽度;在这种情况下,它将无法扩展
  • 向场景中添加线
  • 将线设置为具有最低z值,以便在绘制其他线之前绘制线
例如:

from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtGui import QPen
from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView

scale_fac = 1

def scale():
    global scale_fac
    scale_fac = scale_fac * 1.5
    view.scale(scale_fac, scale_fac)

app = QApplication([])

scene = QGraphicsScene()
pen = QPen(Qt.red)
pen.setCosmetic(True)  # ***
for x in range(0, 500, 50):
    line = scene.addLine( x, 0, x, 500, pen)
    line.setZValue(-10)
for y in range(0, 500, 50):
    scene.addLine( 0, y, 500, y, pen)
    line.setZValue(-10)

view = QGraphicsView()
view.setScene(scene)
view.show()

QTimer.singleShot(1000, scale)
QTimer.singleShot(2000, scale)
QTimer.singleShot(3000, scale)
app.exec()
如果未发出
setcosmatic(True)
,则放大时线条厚度将增加


上述方法的好处在于,这些线位于场景中的固定坐标处。但是,如果缩小,可能需要添加更多线,或使现有线更长。您可以通过覆盖场景的
trabackground()
来实现这一点,它将使用视图中场景的rect调用:在那里您可以调整线端点

Hmm,我发现我还可以设置背景颜色,而不影响网格:

    self.setObjectName("QGraphicsView")
    frame_css = '''
     QGraphicsView#QGraphicsView {
         background-color: rgb(42,42,42);
     }
     '''

    self.setStyleSheet(frame_css)