I need to implement the undo functionality in this widget, activated with the key combination Ctrl + Z. I can draw lines on an image passed in input to the constructor. The idea is therefore to remove the last item from the list of lines (I add a line to this list every time I draw one) and redraw all the other lines when pressing Ctrl + Z. How can I implement this refresh? Is there a more effective way to do such a thing?
Code:
from PyQt5 import QtWidgets, Qt
from PyQt5.QtCore import QSize, QPoint
from PyQt5.QtGui import QImage
import numpy as np
import sys
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QPixmap, QPainter, QPen
class DistanceWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(DistanceWindow, self).__init__(parent)
self.axial = np.random.rand(512, 512)
print(self.axial.shape)
self.axial = QPixmap(QImage(self.axial, self.axial.shape[1], self.axial.shape[0], QImage.Format_Indexed8))
self.axialWidget = DrawWidget(self.axial)
class DrawWidget(QtWidgets.QWidget):
def __init__(self, image):
super().__init__()
self.drawing = False
self.startPoint = None
self.endPoint = None
self.image = image
self.setGeometry(100, 100, 500, 300)
self.resize(self.image.width(), self.image.height())
self.show()
self.lines = []
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.startPoint = event.pos()
def mouseMoveEvent(self, event):
if self.startPoint:
self.endPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if self.startPoint and self.endPoint:
self.updateImage()
def paintEvent(self, event):
painter = QPainter(self)
dirtyRect = event.rect()
painter.drawImage(dirtyRect, QImage(self.image), dirtyRect)
if self.startPoint and self.endPoint:
painter.drawLine(self.startPoint, self.endPoint)
def updateImage(self):
if self.startPoint and self.endPoint:
painter = QPainter(self.image)
painter.setPen(QPen(Qt.red, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.startPoint, self.endPoint)
firstPoint = np.array([self.startPoint.x(), self.startPoint.y()])
secondPoint = np.array([self.endPoint.x(), self.endPoint.y()])
distance = np.sqrt((secondPoint[0]-firstPoint[0])**2 + (secondPoint[1]-firstPoint[1])**2)
painter.setPen(QPen(Qt.yellow))
painter.drawText(secondPoint[0], secondPoint[1] + 10, str(distance) + 'mm')
#line info
line = {}
line['points'] = [self.startPoint, self.endPoint]
line['distance'] = distance
self.lines.append(line)
#####################################
painter.end()
self.startPoint = self.endPoint = None
self.update()
def keyPressEvent(self, event):
if event.key() == (Qt.Key_Control and Qt.Key_Z):
self.undo()
def undo(self):
#Delete the last line from self.lines and draw all the others
if __name__ == '__main__':
app = QApplication(sys.argv)
main = DistanceWindow()
sys.exit(app.exec_())