Can I customize own brushstyle?

952 Views Asked by At

Here are some predefined QbrushStyle for Qbrush, I am wondering is there any chance I can customize a style follow my own will. Thank you.

enter image description here

1

There are 1 best solutions below

1
On BEST ANSWER

You have to create a QPixmap that represents the pattern and set it as a texture to the 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_())

enter image description here

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