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_())
Related
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_())
i'm loading an image on a label supposed after that
a mouse click event that draws dots on the label but dots are drawn on the main window ( behind the label )
GUI Image
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super(ApplicationWindow, self).__init__()
uic.loadUi('MainWindow.ui', self)
self.setFixedSize(self.size())
self.show()
self.points = QtGui.QPolygon()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def mousePressEvent(self, e):
self.points << e.pos()
self.update()
def paintEvent(self, ev):
qp = QtGui.QPainter(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing)
pen = QtGui.QPen(QtCore.Qt.red, 5)
brush = QtGui.QBrush(QtCore.Qt.red)
qp.setPen(pen)
qp.setBrush(brush)
for i in range(self.points.count()):
# qp.drawEllipse(self.points.point(i), 5, 5)
# or
qp.drawPoints(self.points)
def main():
app = QtWidgets.QApplication(sys.argv)
application = ApplicationWindow()
application.show()
sys.exit(app.exec_())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = ApplicationWindow()
sys.exit(app.exec_())
main()
You are calling QPainter(self) so the paint device is the MainWindow. Instead call QPainter on the QPixmap. Here is an example.
class Template(QWidget):
def __init__(self):
super().__init__()
self.lbl = QLabel()
self.pix = QPixmap('photo.jpeg')
grid = QGridLayout(self)
grid.addWidget(self.lbl, 0, 0)
self.points = QPolygon()
def mousePressEvent(self, event):
self.points << QPoint(event.x() - self.lbl.x(), event.y() - self.lbl.y())
def paintEvent(self, event):
qp = QPainter(self.pix)
qp.setRenderHint(QPainter.Antialiasing)
pen = QPen(Qt.red, 5)
brush = QBrush(Qt.red)
qp.setPen(pen)
qp.setBrush(brush)
qp.drawPoints(self.points)
self.lbl.setPixmap(self.pix)
However a better way is to use QImage in a custom widget that will act as a canvas.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Canvas(QWidget):
def __init__(self, photo, *args, **kwargs):
super().__init__(*args, **kwargs)
self.image = QImage(photo)
self.setFixedSize(self.image.width(), self.image.height())
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
qp = QPainter(self.image)
qp.setRenderHint(QPainter.Antialiasing)
qp.setPen(QPen(Qt.red, 5))
qp.setBrush(Qt.red)
qp.drawPoint(event.pos())
self.update()
def paintEvent(self, event):
qp = QPainter(self)
rect = event.rect()
qp.drawImage(rect, self.image, rect)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
w = QWidget()
self.setCentralWidget(w)
grid = QGridLayout(w)
grid.addWidget(Canvas('photo.jpeg'))
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = MainWindow()
gui.show()
sys.exit(app.exec_())
Output:
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())
I am using PyQt5 to build a GUI and inside it I am using a Class Drawer to enable for the user to draw using the mouse but when I am saving the image it is always empty can any one tell me why?
class Drawer(QWidget):
newPoint = pyqtSignal(QPoint)
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setAttribute(QtCore.Qt.WA_StaticContents)
self.modified = False
self.scribbling = False
imageSize = QtCore.QSize(9500, 9500)
h=400
w=400
self.myPenWidth = 13
self.myPenColor = QtCore.Qt.black
self.image = QtGui.QImage()
self.image=QtGui.QImage(w,h,QtGui.QImage.Format_RGB32)
self.path = QPainterPath()
def setPenColor(self, newColor):
self.myPenColor = newColor
def setPenWidth(self, newWidth):
self.myPenWidth = newWidth
def clearImage(self):
self.path = QPainterPath()
self.image.fill(QtGui.qRgb(255, 255, 255)) ## switch it to else
self.modified = True
self.update()
def saveImage(self, fileName, fileFormat):
self.image.save(fileName,fileFormat)
def paintEvent(self, event):
painter = QPainter(self)
#painter.setPen(QColor(0, 0, 0))
painter.setPen(QtGui.QPen(self.myPenColor,
self.myPenWidth,QtCore.Qt.SolidLine, QtCore.Qt.RoundCap,
QtCore.Qt.RoundJoin))
#painter.setFont(QFont('Decorative', 10))
painter.drawImage(event.rect(), self.image)
painter.drawPath(self.path)
def mousePressEvent(self, event):
self.path.moveTo(event.pos())
self.update()
def mouseMoveEvent(self, event):
self.path.lineTo(event.pos())
self.newPoint.emit(event.pos())
self.update()
def sizeHint(self):
return QSize(300, 300)
when I am calling it i use this function that calls the function inside the Drawer class
def saveFile(self):#, fileFormat):
fileFormat="PNG"
fileName="ar.png"
self.draw2.saveImage(fileName,fileFormat)
It is always empty because you have never painted the image, what you have painted has been the background of the QWidget, in the following code I have created a QPainter that takes as a base the image and draws on it and in the paintEvent() only the image is painted :
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Drawer(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setAttribute(Qt.WA_StaticContents)
h = 400
w = 400
self.myPenWidth = 13
self.myPenColor = Qt.black
self.image = QImage(w, h, QImage.Format_RGB32)
self.path = QPainterPath()
self.clearImage()
def setPenColor(self, newColor):
self.myPenColor = newColor
def setPenWidth(self, newWidth):
self.myPenWidth = newWidth
def clearImage(self):
self.path = QPainterPath()
self.image.fill(Qt.white) ## switch it to else
self.update()
def saveImage(self, fileName, fileFormat):
self.image.save(fileName, fileFormat)
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(event.rect(), self.image, self.rect())
def mousePressEvent(self, event):
self.path.moveTo(event.pos())
def mouseMoveEvent(self, event):
self.path.lineTo(event.pos())
p = QPainter(self.image)
p.setPen(QPen(self.myPenColor,
self.myPenWidth, Qt.SolidLine, Qt.RoundCap,
Qt.RoundJoin))
p.drawPath(self.path)
p.end()
self.update()
def sizeHint(self):
return QSize(300, 300)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
btnSave = QPushButton("Save image")
btnClear = QPushButton("Clear")
drawer = Drawer()
w.setLayout(QVBoxLayout())
w.layout().addWidget(btnSave)
w.layout().addWidget(btnClear)
w.layout().addWidget(drawer)
btnSave.clicked.connect(lambda: drawer.saveImage("image.png", "PNG"))
btnClear.clicked.connect(drawer.clearImage)
w.show()
sys.exit(app.exec_())
I'm trying to paint some ticks in my custom progressbar but I'm not clear on why the line isn't showing up at all?
import sys
import os
sys.path.append('Z:\\pipeline\\site-packages')
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from PySide import QtGui, QtCore
class QProgressBarPro(QtGui.QProgressBar):
progressClicked = QtCore.Signal()
progressChanging = QtCore.Signal()
progressChanged = QtCore.Signal()
def __init__(self, parent=None):
super(QProgressBarPro, self).__init__(parent)
self.default_value = 50.0
self.lmb_pressed = False
self.setFormat('%p')
self.setRange(0.0, 100.0)
self.stepEnabled = True
self.step = 5
self.setToolTip('<strong>Press+Hold+Ctrl</strong> for percise values<br><strong>Right-Click</strong> to reset default value')
def step_round(self, x, base=5):
return int(base * round(float(x)/base))
def set_value_from_cursor(self, xpos):
width = self.frameGeometry().width()
percent = float(xpos) / width
val = self.maximum() * percent
if self.stepEnabled:
modifiers = QtGui.QApplication.keyboardModifiers()
if modifiers != QtCore.Qt.ControlModifier:
val = self.step_round(val, self.step)
self.setValue(val)
def mousePressEvent(self, event):
self.progressClicked.emit()
mouse_button = event.button()
if mouse_button == QtCore.Qt.RightButton:
self.setValue(self.default_value)
else:
xpos = event.pos().x()
self.set_value_from_cursor(xpos)
self.lmb_pressed = True
self.progressChanging.emit()
def mouseReleaseEvent(self, event):
self.lmb_pressed = False
self.progressChanged.emit()
def mouseMoveEvent(self, event):
if self.lmb_pressed:
xpos = event.pos().x()
self.set_value_from_cursor(xpos)
self.progressChanging.emit()
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.drawLine(10, 0, 10, 10)
QtGui.QProgressBar.paintEvent(self, event)
# DEMO
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.ui_progress = QProgressBarPro()
self.ui_progress.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.ui_progress.setValue(10)
gdl = QtGui.QVBoxLayout()
gdl.addWidget(self.ui_progress)
self.setLayout(gdl)
self.resize(300, 300)
self.setWindowTitle('Tooltips')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You need to change your paintEvent function.
I wrote a first approach that provides same result as in your image:
def paintEvent(self, event):
QtGui.QProgressBar.paintEvent(self, event)
painter = QtGui.QPainter(self)
brush = QtGui.QBrush(QtCore.Qt.SolidPattern)
# Set gray color
brush.setColor(QtGui.QColor(204,204,204))
painter.setPen(QtGui.QPen(brush, 2, QtCore.Qt.SolidLine,QtCore.Qt.RoundCap))
#print(str(self.width())+","+str(self.height()))
progressbarwidth = self.width()
progressbarheight = self.height()
## Drawing one vertical line each 1/5
painter.drawLine(progressbarwidth*1/5, 0, progressbarwidth*1/5, progressbarheight)
painter.drawLine(progressbarwidth*2/5, 0, progressbarwidth*2/5, progressbarheight)
painter.drawLine(progressbarwidth*3/5, 0, progressbarwidth*3/5, progressbarheight)
painter.drawLine(progressbarwidth*4/5, 0, progressbarwidth*4/5, progressbarheight)
The achieved outcome is shown here.