Search code examples
pythonpyqtpyqt5qgraphicsitem

Associating a picture with a QGraphicsItem


I want a picture displayed where the QGraphicsItem is. Is this possible with QGraphicsRectItem? I have tried to look some classes in Qt library but couldn't find any under QGraphicsItem.

Here is code where I create basic QGraphicsItem, but from here couldn't find way to add the image.

obstacle = QtWidgets.QGraphicsRectItem(-100, 490, 175, 40)
obstacle.setBrush(QtGui.QBrush(QtGui.QColor(128,0,128), QtCore.Qt.SolidPattern))
self.scene.addItem(obstacle)

Solution

  • If you want to add an image to QGraphicsScene use a QGraphicsPixmapItem or the addPixmap() method:

    pixmap_item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap("path/of/image"))
    self.scene.addItem(pixmap_item)
    

    Or

    pixmap_item = self.scene.addPixmap(QtGui.QPixmap("path/of/image"))