Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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):
            super().__init__()
            self.resize(600, 400)
            self.begin = QtCore.QPoint()
            self.end = QtCore.QPoint()
            self.pix = QtGui.QPixmap(600, 400)
            self.pix.fill(QtCore.Qt.white)
    
        def paintEvent(self, event):
            qp = QtGui.QPainter(self)
            qp.drawPixmap(0, 0, self.pix)
            br = QtGui.QBrush(QtGui.QColor("transparent"))
            qp.setBrush(br)
            if self.begin and self.end:
                rect = QtCore.QRect(self.begin, self.end)
                qp.drawRect(rect)
    
        def mousePressEvent(self, event):
            if event.button() == QtCore.Qt.LeftButton:
                self.begin = event.pos()
                self.end = self.begin
                self.update()
    
        def mouseMoveEvent(self, event):
            if event.buttons() == QtCore.Qt.LeftButton:
                self.end = event.pos()
                self.update()
    
        def mouseReleaseEvent(self, event):
            if event.button() == QtCore.Qt.LeftButton:
                painter = QtGui.QPainter(self.pix)
                rect = QtCore.QRect(self.begin, self.end)
                painter.drawRect(rect)
                self.begin = self.end = QtCore.QPoint()
                self.update()
    
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        window = MyWidget()
        window.show()
        sys.exit(app.exec_())
    
    
    

    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