您需要创建一个代表模式的QPixmap,并将其设置为QBrush的纹理:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
def create_texture():
pixmap = QtGui.QPixmap(QtCore.QSize(8, 8))
pixmap.fill(QtGui.QColor("red"))
painter = QtGui.QPainter(pixmap)
painter.setBrush(QtGui.QBrush(QtGui.QColor("blue")))
painter.drawEllipse(pixmap.rect())
painter.end()
return pixmap
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
texture = create_texture()
brush = QtGui.QBrush()
brush.setTexture(texture)
scene = QtWidgets.QGraphicsScene()
view = QtWidgets.QGraphicsView(scene)
it = scene.addRect(QtCore.QRectF(0, 0, 400, 400))
it.setBrush(brush)
view.resize(640, 480)
view.show()
sys.exit(app.exec_())
或者QImage:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
def create_texture():
image = QtGui.QImage(QtCore.QSize(8, 8), QtGui.QImage.Format_ARGB32)
image.fill(QtGui.QColor("red"))
painter = QtGui.QPainter(image)
painter.setBrush(QtGui.QBrush(QtGui.QColor("blue")))
painter.drawEllipse(image.rect())
painter.end()
return image
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
texture = create_texture()
brush = QtGui.QBrush()
brush.setTextureImage(texture)
scene = QtWidgets.QGraphicsScene()
view = QtWidgets.QGraphicsView(scene)
it = scene.addRect(QtCore.QRectF(0, 0, 400, 400))
it.setBrush(brush)
view.resize(640, 480)
view.show()
sys.exit(app.exec_())