着色QPolygonItem

问题描述 投票:1回答:1

如何为QPolygonF项目着色?我已经创建了三角形,但不知道如何填充某些颜色。

我试图在Qt库中找到类,但没有找到任何类。这是我创建三角形并将其添加到场景的代码。我试图使用setBrush()函数,但QPolygonF没有该类..

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)
python pyqt pyqt5
1个回答
0
投票

当您使用addPolygon方法时,它返回一个QGraphicsPolygonItem,并且GraphicsPolygonItem继承自QAbstractGraphicsShapeItem,该类可以使用setBrush()方法更改填充颜色,使用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

© www.soinside.com 2019 - 2024. All rights reserved.