1

How can I color my QPolygonF item? I have created triangle but don't know how to fill it with certain color.

I tried to find class in Qt library but didn't find any. Here is code where I create the triangle and add it to the scene. I tried to use setBrush() function, but QPolygonF doesn't have that class..

triangle = QtGui.QPolygonF()
triangle.append(QtCore.QPointF(0,550)) # Bottom-left
triangle.append(QtCore.QPointF(50, 550)) # Bottom-right
triangle.append(QtCore.QPointF(25, 525)) # Tip
self.scene.addPolygon(triangle)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Nar Bob
  • 69
  • 1
  • 1
  • 5
  • see https://stackoverflow.com/questions/53807573/efficient-way-to-move-qgraphicitems-inside-qgraphicsscene – S. Nick Apr 04 '19 at 17:32

1 Answers1

1

When you use the addPolygon method this returns a QGraphicsPolygonItem, and that GraphicsPolygonItem inherits from QAbstractGraphicsShapeItem, and that class gives the ability to change the fill color using the setBrush() method and the border color with setPen():

from PyQt5 import QtCore, QtGui, QtWidgets


class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)
        self.setScene(QtWidgets.QGraphicsScene(self))
        triangle = QtGui.QPolygonF()
        triangle.append(QtCore.QPointF(0, 550))  # Bottom-left
        triangle.append(QtCore.QPointF(50, 550))  # Bottom-right
        triangle.append(QtCore.QPointF(25, 525))  # Tip
        triangle_item = self.scene().addPolygon(triangle)
        triangle_item.setBrush(QtGui.QBrush(QtGui.QColor("salmon")))
        triangle_item.setPen(QtGui.QPen(QtGui.QColor("gray")))


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = GraphicsView()
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241