Erasing pen on a canvas - python

I have a functioning drawing application for some segmentation on images. For this I have two layers, the original image and the image layer I am drawing on.
I now want to implement a method for erasing. I have implemented undo functionality, but I would also like the user to be able to select a brush "color" as to be able to erase specific parts, like the eraser in paint. I thought this would be possible by drawing with a color with opacity, but that just results in no line being drawn.
The goal for me is therefore to draw a line, that removes the pixel values in the image layer, such that I can see the underlying image
MVP of drawing
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QMenu, QAction
from PyQt5.QtGui import QIcon, QImage, QPainter, QPen
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QColor
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
top = 400
left = 400
width = 800
height = 600
self.setWindowTitle("MyPainter")
self.setGeometry(top, left, width, height)
self.image = QImage(self.size(), QImage.Format_ARGB32)
self.image.fill(Qt.white)
self.imageDraw = QImage(self.size(), QImage.Format_ARGB32)
self.imageDraw.fill(Qt.transparent)
self.drawing = False
self.brushSize = 2
self.brushColor = Qt.black
self.lastPoint = QPoint()
self.change = False
mainMenu = self.menuBar()
changeColour = mainMenu.addMenu("changeColour")
changeColourAction = QAction("change",self)
changeColour.addAction(changeColourAction)
changeColourAction.triggered.connect(self.changeColour)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton and self.drawing:
painter = QPainter(self.imageDraw)
painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button == Qt.LeftButton:
self.drawing = False
def paintEvent(self, event):
canvasPainter = QPainter(self)
canvasPainter.drawImage(self.rect(), self.image, self.image.rect())
canvasPainter.drawImage(self.rect(), self.imageDraw, self.imageDraw.rect())
def changeColour(self):
if not self.change:
# erase
self.brushColor = QColor(255,255,255,0)
else:
self.brushColor = Qt.black
self.change = not self.change
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec()
How to erase a subset of pixels?
As in this example what color should be given to self.brushColor in the changeColour function?
Info
The colour white is not the solution, because in reality the image at the bottom is a complex image, I therefore want to make the toplayer "see-through" again, when erasing.

You have to change the compositionMode to QPainter::CompositionMode_Clear and erase with eraseRect().
from PyQt5 import QtCore, QtGui, QtWidgets
class Window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
top, left, width, height = 400, 400, 800, 600
self.setWindowTitle("MyPainter")
self.setGeometry(top, left, width, height)
self.image = QtGui.QImage(self.size(), QtGui.QImage.Format_ARGB32)
self.image.fill(QtCore.Qt.white)
self.imageDraw = QtGui.QImage(self.size(), QtGui.QImage.Format_ARGB32)
self.imageDraw.fill(QtCore.Qt.transparent)
self.drawing = False
self.brushSize = 2
self._clear_size = 20
self.brushColor = QtGui.QColor(QtCore.Qt.black)
self.lastPoint = QtCore.QPoint()
self.change = False
mainMenu = self.menuBar()
changeColour = mainMenu.addMenu("changeColour")
changeColourAction = QtWidgets.QAction("change", self)
changeColour.addAction(changeColourAction)
changeColourAction.triggered.connect(self.changeColour)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() and QtCore.Qt.LeftButton and self.drawing:
painter = QtGui.QPainter(self.imageDraw)
painter.setPen(QtGui.QPen(self.brushColor, self.brushSize, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
if self.change:
r = QtCore.QRect(QtCore.QPoint(), self._clear_size*QtCore.QSize())
r.moveCenter(event.pos())
painter.save()
painter.setCompositionMode(QtGui.QPainter.CompositionMode_Clear)
painter.eraseRect(r)
painter.restore()
else:
painter.drawLine(self.lastPoint, event.pos())
painter.end()
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button == QtCore.Qt.LeftButton:
self.drawing = False
def paintEvent(self, event):
canvasPainter = QtGui.QPainter(self)
canvasPainter.drawImage(self.rect(), self.image, self.image.rect())
canvasPainter.drawImage(self.rect(), self.imageDraw, self.imageDraw.rect())
def changeColour(self):
self.change = not self.change
if self.change:
pixmap = QtGui.QPixmap(QtCore.QSize(1, 1)*self._clear_size)
pixmap.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(pixmap)
painter.setPen(QtGui.QPen(QtCore.Qt.black, 2))
painter.drawRect(pixmap.rect())
painter.end()
cursor = QtGui.QCursor(pixmap)
QtWidgets.QApplication.setOverrideCursor(cursor)
else:
QtWidgets.QApplication.restoreOverrideCursor()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())

Related

use mouse drag to change the width of a rectangle?

I got this code that helps me draw a rectangle from another SO answer, I'd like to be able to drag the left and right sides of the rectangle to adjust the width of the rectangle, make the rectangle behave in a way similar to how you crop an image on most photo editing software, where you draw the initial area but you have the possibility to adjust the width afterwards to get the crop you want.
the code I have so far:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30,30,600,400)
self.begin = QPoint()
self.end = QPoint()
self.show()
def paintEvent(self, event):
qp = QPainter(self)
br = QBrush(QColor(100, 10, 10, 40))
qp.setBrush(br)
qp.drawRect(QRect(self.begin, self.end))
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = event.pos()
# print(f"press begin {self.begin}")
# print(f"press end {self.end}")
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
def mouseReleaseEvent(self, event):
#self.begin = event.pos()
self.end = event.pos()
#self.update()
print(f"begin {self.begin}")
print(f"end {self.end}")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWidget()
window.show()
app.aboutToQuit.connect(app.deleteLater)
sys.exit(app.exec_())
I found the answer to this on a PyQt forum, courtesy of a man by the name of Salem Bream, he answered my question, I thought I'd share it with the SO community.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
FREE_STATE = 1
BUILDING_SQUARE = 2
BEGIN_SIDE_EDIT = 3
END_SIDE_EDIT = 4
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 600, 400)
self.begin = QPoint()
self.end = QPoint()
self.state = FREE_STATE
def paintEvent(self, event):
qp = QPainter(self)
br = QBrush(QColor(100, 10, 10, 40))
qp.setBrush(br)
qp.drawRect(QRect(self.begin, self.end))
def mousePressEvent(self, event):
if not self.begin.isNull() and not self.end.isNull():
p = event.pos()
y1, y2 = sorted([self.begin.y(), self.end.y()])
if y1 <= p.y() <= y2:
# 3 resolution, more easy to pick than 1px
if abs(self.begin.x() - p.x()) <= 3:
self.state = BEGIN_SIDE_EDIT
return
elif abs(self.end.x() - p.x()) <= 3:
self.state = END_SIDE_EDIT
return
self.state = BUILDING_SQUARE
self.begin = event.pos()
self.end = event.pos()
self.update()
def applye_event(self, event):
if self.state == BUILDING_SQUARE:
self.end = event.pos()
elif self.state == BEGIN_SIDE_EDIT:
self.begin.setX(event.x())
elif self.state == END_SIDE_EDIT:
self.end.setX(event.x())
def mouseMoveEvent(self, event):
self.applye_event(event)
self.update()
def mouseReleaseEvent(self, event):
self.applye_event(event)
self.state = FREE_STATE
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWidget()
window.show()
app.aboutToQuit.connect(app.deleteLater)
sys.exit(app.exec_())

How to draw line with brush on image with PyQt5

I want to draw a line (or paint) on an image that I already opened. I can open the image, but I can't draw on the image. But if I don't open any image, I can draw anything I want on blank space.
So, How can I draw with a brush on an image ? For now eraser or etc. It's not important. I just want to do something with a brush on an image, which image I already open in my computer.
I didn't get any error or something. So I can't search specifically.
Here is my code;
from PyQt5.QtWidgets import QMainWindow, QApplication, QMenu, QMenuBar, QAction, QFileDialog, QLabel
from PyQt5.QtGui import QIcon, QImage, QPainter, QPen, QBrush, QPixmap
from PyQt5.QtCore import Qt, QPoint
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
title = "Paint Application"
top = 400
left = 400
width = 800
height = 600
icon = "icons/pain.png"
self.setWindowTitle(title)
self.setGeometry(top, left, width, height)
self.setWindowIcon(QIcon(icon))
self.image = QImage(self.size(), QImage.Format_RGB32)
self.image.fill(Qt.white)
self.drawing = False
self.brushSize = 2
self.brushColor = Qt.black
self.lastPoint = QPoint()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu("File")
brushSize = mainMenu.addMenu("Brush Size")
brushColor = mainMenu.addMenu("Brush Color")
openAction = QAction('Open Image', self)
openAction.triggered.connect(self.openImage)
fileMenu.addAction(openAction)
closeAction = QAction('Exit', self)
closeAction.triggered.connect(self.close)
fileMenu.addAction(closeAction)
self.label = QLabel()
self.setCentralWidget(self.label)
saveAction = QAction(QIcon("icons/save.png"), "Save",self)
saveAction.setShortcut("Ctrl+S")
fileMenu.addAction(saveAction)
saveAction.triggered.connect(self.save)
clearAction = QAction(QIcon("icons/clear.png"), "Clear", self)
clearAction.setShortcut("Ctrl+C")
fileMenu.addAction(clearAction)
clearAction.triggered.connect(self.clear)
threepxAction = QAction( QIcon("icons/threepx.png"), "3px", self)
brushSize.addAction(threepxAction)
threepxAction.triggered.connect(self.threePixel)
fivepxAction = QAction(QIcon("icons/fivepx.png"), "5px", self)
brushSize.addAction(fivepxAction)
fivepxAction.triggered.connect(self.fivePixel)
sevenpxAction = QAction(QIcon("icons/sevenpx.png"),"7px", self)
brushSize.addAction(sevenpxAction)
sevenpxAction.triggered.connect(self.sevenPixel)
ninepxAction = QAction(QIcon("icons/ninepx.png"), "9px", self)
brushSize.addAction(ninepxAction)
ninepxAction.triggered.connect(self.ninePixel)
blackAction = QAction(QIcon("icons/black.png"), "Black", self)
blackAction.setShortcut("Ctrl+B")
brushColor.addAction(blackAction)
blackAction.triggered.connect(self.blackColor)
whitekAction = QAction(QIcon("icons/white.png"), "White", self)
whitekAction.setShortcut("Ctrl+W")
brushColor.addAction(whitekAction)
whitekAction.triggered.connect(self.whiteColor)
redAction = QAction(QIcon("icons/red.png"), "Red", self)
redAction.setShortcut("Ctrl+R")
brushColor.addAction(redAction)
redAction.triggered.connect(self.redColor)
greenAction = QAction(QIcon("icons/green.png"), "Green", self)
greenAction.setShortcut("Ctrl+G")
brushColor.addAction(greenAction)
greenAction.triggered.connect(self.greenColor)
yellowAction = QAction(QIcon("icons/yellow.png"), "Yellow", self)
yellowAction.setShortcut("Ctrl+Y")
brushColor.addAction(yellowAction)
yellowAction.triggered.connect(self.yellowColor)
def openImage(self):
imagePath, _ = QFileDialog.getOpenFileName()
pixmap = QPixmap(imagePath)
self.label.setPixmap(pixmap)
self.resize(pixmap.size())
self.adjustSize()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
#print(self.lastPoint)
def mouseMoveEvent(self, event):
if(event.buttons() & Qt.LeftButton) & self.drawing:
painter = QPainter(self.image)
painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = False
def paintEvent(self, event):
canvasPainter = QPainter(self)
canvasPainter.drawImage(self.rect(),self.image, self.image.rect() )
def save(self):
filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")
if filePath == "":
return
self.image.save(filePath)
def clear(self):
self.image.fill(Qt.white)
self.update()
def threePixel(self):
self.brushSize = 3
def fivePixel(self):
self.brushSize = 5
def sevenPixel(self):
self.brushSize = 7
def ninePixel(self):
self.brushSize = 9
def blackColor(self):
self.brushColor = Qt.black
def whiteColor(self):
self.brushColor = Qt.white
def redColor(self):
self.brushColor = Qt.red
def greenColor(self):
self.brushColor = Qt.green
def yellowColor(self):
self.brushColor = Qt.yellow
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec()
Instead of constructing a QPixmap from the filepath, construct a QImage and assign it to the variable self.image. You won't have to change anything else as the paintEvent will draw the QImage object that pointed to by self.image.
def openImage(self):
imagePath, _ = QFileDialog.getOpenFileName()
self.image = QImage(imagePath)
self.resize(self.image.size())

Insert Image into QGridLayout and Draw on top of image in PyQt5

I'm pretty new to PyQt and am trying to make an application with a QPixmap on the left, which can be drawn on, and a QTextEdit on the right (for a simple OCR GUI).
I looked at:
PyQt5 Image and QGridlayout
but I couldn't connect it with the code below (I'm losing my hair with all the head scratching!!)
When I try adapting the following code, what I get is a QMainWindow with the QPixmap as the background which can be drawn on with the mouse and a second occurance of the QPixmap in it's correct position, which can not be drawn on. Can someone tell me what I'm doing wrong?
Thank you very much!
# https://stackoverflow.com/questions/51475306/
import sys
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QMainWindow, QApplication,QGridLayout, QLabel, QWidget, QTextEdit
from PyQt5.QtGui import QPixmap, QPainter, QPen
class Menu(QMainWindow):
def __init__(self):
super().__init__()
self.drawing = False
self.lastPoint = QPoint()
self.image = QPixmap("S3.png")
self.setGeometry(100, 100, 500, 300)
self.resize(self.image.width(), self.image.height())
layout = QGridLayout()
# Add a QTextEdit box
self.edit = QTextEdit()
layout.addWidget(self.edit, 0, 0, 10, 20)
# This:
# https://stackoverflow.com/questions/52616553
# indicates that a QPixmap must be put into a label to insert into a QGridLayout
self.label = QLabel()
self.label.setPixmap(self.image)
layout.addWidget(self.label, 10, 20, 10, 20)
# https://stackoverflow.com/questions/37304684/
self.widget = QWidget()
self.widget.setLayout(layout)
self.setCentralWidget(self.widget)
self.show()
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(self.rect(), self.image)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
print(self.lastPoint)
def mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton and self.drawing:
painter = QPainter(self.image)
painter.setPen(QPen(Qt.red, 3, Qt.SolidLine))
painter.drawLine(self.lastPoint, event.pos())
print(self.lastPoint,event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button == Qt.LeftButton:
self.drawing = False
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
sys.exit(app.exec_())
Each widget must fulfill a specific task, so I have created a widget that only has the painted function, the main widget works as a container for the painting widget and the QTextEdit.
from PyQt5 import QtCore, QtGui, QtWidgets
class Label(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Label, self).__init__(parent)
self.image = QtGui.QPixmap("S3.png")
self.drawing = False
self.lastPoint = QtCore.QPoint()
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(QtCore.QPoint(), self.image)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() and QtCore.Qt.LeftButton and self.drawing:
painter = QtGui.QPainter(self.image)
painter.setPen(QtGui.QPen(QtCore.Qt.red, 3, QtCore.Qt.SolidLine))
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button == QtCore.Qt.LeftButton:
self.drawing = False
def sizeHint(self):
return self.image.size()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.label = Label()
self.textedit = QtWidgets.QTextEdit()
widget = QtWidgets.QWidget()
self.setCentralWidget(widget)
lay = QtWidgets.QHBoxLayout(widget)
lay.addWidget(self.label, alignment=QtCore.Qt.AlignCenter)
lay.addWidget(self.textedit)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

PyQT5: How to interactively paint on image within QLabel Widget? [duplicate]

This question already has an answer here:
Drawing with a brush
(1 answer)
Closed 4 years ago.
Python 3, latest version of PyQt5 on Mac OS Mojave
I want a PyQt5 program in which the user could paint connected dots on an image (click distinctively and the points are automatically connected). It is important that I can only draw on the image in the QLabel widget (or an alternative widget) and not over the entire main window.
I can plot the image and get the the coordinates of the previous two clicks but when I want to paint on the image it happens underneath the image. Further I have troubles in getting the coordinates as input for my paintevent.
class Example(QWidget):
def __init__(self):
super().__init__()
title = "Darcy"
top = 400
left = 400
width = 550
height = 600
self.clickcount = 0
self.x = 0
self.y = 0
self.setWindowTitle(title)
self.setGeometry(top,left, width, height)
self.initUI()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawLines(qp)
qp.end()
def drawLines(self, qp):
pen = QPen(Qt.black, 2, Qt.SolidLine)
qp.setPen(pen)
qp.drawLine(20, 40, 250, 40)
def initUI(self):
self.map = QLabel()
Im = QPixmap("GM_loc.png")
Im = Im.scaled(450,450)
self.map.setPixmap(Im)
self.loc = QLabel()
self.test = QLabel()
self.map.mousePressEvent = self.getPos
#organize in grid
grid = QGridLayout()
grid.setSpacing(10)
grid.addWidget(self.map, 0, 0)
grid.addWidget(self.loc,1,0)
grid.addWidget(self.test,2,0)
self.setLayout(grid)
self.show()
def getPos(self , event):
self.clickcount += 1
self.x_old = self.x
self.y_old = self.y
self.x = event.pos().x()
self.y = event.pos().y()
self.loc.setText("x = "+str(self.x)+" & y= "+str(self.y)+" & old x = " + str(self.x_old) + " & old y = " + str(self.y_old))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Thanks in advance!
PS I am a rookie in PyQt5 so any hints in more efficient code are more than welcome!
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class MyScribbling(QMainWindow):
def __init__(self):
super().__init__()
self.penOn = QAction(QIcon('Image/ok.png'), 'ON drawing', self)
self.penOn.triggered.connect(self.drawingOn)
self.penOff = QAction(QIcon('Image/exit.png'), 'OFF drawing', self)
self.penOff.triggered.connect(self.drawingOff)
toolbar = self.addToolBar('Tools')
toolbar.addAction(self.penOn)
toolbar.addAction(self.penOff)
self.scribbling = False
self.myPenColor = Qt.red
self.myPenWidth = 3
self.lastPoint = QPoint()
self.image = QPixmap("Image/picture.png")
self.setFixedSize(600, 600)
self.resize(self.image.width(), self.image.height())
self.setWindowTitle("drawing On / Off")
def paintEvent(self, event):
painter = QPainter(self)
painter.drawPixmap(self.rect(), self.image)
def mousePressEvent(self, event):
if (event.button() == Qt.LeftButton) and self.scribbling:
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton) and self.scribbling:
painter = QPainter(self.image)
painter.setPen(QPen(self.myPenColor, self.myPenWidth,
Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def drawingOn(self):
self.scribbling = True
def drawingOff(self):
self.scribbling = False
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyScribbling()
ex.show()
sys.exit(app.exec_())

Qt5 scribble with layers - QPaintDevice: cannot destroy device that is being painted

I'm trying to re-implement the scribble demo app for multiple layers of images. I am struggling to draw into the pixmap within the scene as the Painter complains that is being destroyed to early.
QPaintDevice: Cannot destroy paint device that is being painted
Could you please help me fix my code such that you can draw on to the roilayer pixmap with the red pen and that this layer starts transparent.
#!/usr/bin/python3
import sys
import os
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsPixmapItem
from PyQt5.QtGui import QPixmap, QImage, QPainter, QPen
from PyQt5.QtCore import Qt, QRect
class Main(QGraphicsView):
def __init__(self):
super().__init__()
self.setWindowTitle("Scribble with layers")
self.scene = QGraphicsScene()
self.setScene(self.scene)
self.image = QImage('sample/test.bmp')
self.imlayer = QGraphicsPixmapItem(QPixmap.fromImage(self.image))
self.roilayer = QGraphicsPixmapItem(QPixmap(self.image.size()))
self.addlayer(self.imlayer)
self.addlayer(self.roilayer)
self.drawing = False
self.lastPoint = None
self.pencolour = Qt.red
self.penwidth = 2
self.show()
def addlayer(self, layer):
self.scene.addItem(layer)
self.updateviewer()
def updateviewer(self):
self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)
def mousePressEvent(self, event):
# print(event.modifiers())
if event.button() == Qt.LeftButton:
self.lastPoint = event.pos()
self.drawing = True
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton) and self.drawing:
self.drawlineto(event.pos())
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.drawing:
self.drawlineto(event.pos())
self.drawing = False
def drawlineto(self, position):
pixmap = self.roilayer.pixmap()
painter = QPainter(pixmap)
painter.setPen(QPen(self.pencolour, self.penwidth, Qt.SolidLine,
Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, position)
self.imlayer.setPixmap(pixmap)
self.modified = True
rad = self.penwidth / 2 + 2
self.update(QRect(self.lastPoint, position).normalized().adjusted(-rad, -rad, +rad, +rad))
self.lastPoint = position
if __name__ == '__main__':
app = QApplication([])
main = Main()
sys.exit(app.exec_())
I had the same problem. The solution is to do the following to this part of your code:
def drawlineto(self, position):
pixmap = self.roilayer.pixmap()
painter = QPainter()
painter.begin(pixmap)
painter.setPen(QPen(self.pencolour, self.penwidth, Qt.SolidLine,
Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, position)
painter.end()
self.imlayer.setPixmap(pixmap)
self.modified = True

Categories