Important: Please read the Qt Code of Conduct -

Removing drawn PyQt objects

  • this is the code that draws primitives on the image.

    import sys
    from PyQt5 import QtCore, QtGui, QtWidgets 
    class MyWidget(QtWidgets.QWidget):
        def __init__(self):
            self.resize(600, 400)
            self.begin = QtCore.QPoint()
            self.end = QtCore.QPoint()
            self.pix = QtGui.QPixmap(600, 400)
        def paintEvent(self, event):
            qp = QtGui.QPainter(self)
            qp.drawPixmap(0, 0, self.pix)
            br = QtGui.QBrush(QtGui.QColor("transparent"))
            if self.begin and self.end:
                rect = QtCore.QRect(self.begin, self.end)
        def mousePressEvent(self, event):
            if event.button() == QtCore.Qt.LeftButton:
                self.begin = event.pos()
                self.end = self.begin
        def mouseMoveEvent(self, event):
            if event.buttons() == QtCore.Qt.LeftButton:
                self.end = event.pos()
        def mouseReleaseEvent(self, event):
            if event.button() == QtCore.Qt.LeftButton:
                painter = QtGui.QPainter(self.pix)
                rect = QtCore.QRect(self.begin, self.end)
                self.begin = self.end = QtCore.QPoint()
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        window = MyWidget()

    How do I remove the shape correctly now? For example, I put in rectangles and you need to remove the extra ones. Select the desired one with the mouse and delete. How to do it correctly?

  • Lifetime Qt Champion

    @Omg-Zomg said in Removing drawn PyQt objects:

    How to do it correctly?

    What is your question exactly? How to select something you draw with mouse?
    To "remove" something you simply do not draw it anymore.

Log in to reply