PyQt - how to overlay a rectangle on an image

2019-02-20 15:42发布

问题:

After displaying an image on a PyQt label, I want to draw a rectangle on top of the displayed image. Note that I don't mean 'draw' as in where the user 'draws' a rectangle on the image, but I mean that I just want to create a rectangle on top of the image. I have the equivalent code for matplotlib axes but I'm not sure how to do the same thing in PyQt.

# Create Figure/Axes Instance
figure,axes = matplotlib.pyplot.subplots()
axes.imshow(imageRGB)

# Draw Rectangle
axes.add_patch(matplotlib.patches.Rectangle((50,50),100,100,fill=False,edgecolor='red'))

回答1:

# convert image file into pixmap
self.pixmap_image = QtGui.QPixmap(self.filename)

# create painter instance with pixmap
self.painterInstance = QtGui.QPainter(self.pixmap_image)

# set rectangle color and thickness
self.penRectangle = QtGui.QPen(QtCore.Qt.red)
self.penRedBorder.setWidth(3)

# draw rectangle on painter
self.painterInstance.setPen(self.penRectangle)
self.painterInstance.drawRect(xPos,yPos,xLen,yLen)

# set pixmap onto the label widget
self.ui.label_imageDisplay.setPixmap(self.pixmap_image)
self.ui.label_imageDisplay.show()