Dec-30-2021, 07:34 AM
Hi all. I'm having trouble implementing a drawing box in QT5 Designer. This code as an example, creates the window dynamically and uses QPainter and QImage, but there's no QImage widget to drag and drop in QT5 designer I am aware of. I read a few examples with Qlabel and pixmap but this code below looked much cleaner and I was having trouble with inheritance and methods to clear the image.
I have a label on my ui named "lbldrawing", and I would like to know how do I set the QImage to be inside (if that's the correct term) the label container widget?
I would rather use a static widget in the ui than positioning it in code. Any help would be great.
Here's the code (shortened vers) from https://www.geeksforgeeks.org/pyqt5-crea...plication/
I have a label on my ui named "lbldrawing", and I would like to know how do I set the QImage to be inside (if that's the correct term) the label container widget?
I would rather use a static widget in the ui than positioning it in code. Any help would be great.
Here's the code (shortened vers) from https://www.geeksforgeeks.org/pyqt5-crea...plication/
from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Paint with PyQt5 - nice example of painting with python") self.setGeometry(500, 100, 800, 600) 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") saveAction = QAction("Save", self) saveAction.setShortcut("Ctrl + S") fileMenu.addAction(saveAction) saveAction.triggered.connect(self.save) clearAction = QAction("Clear", self) fileMenu.addAction(clearAction) clearAction.triggered.connect(self.clear) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.drawing = True self.lastPoint = event.pos() 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() App = QApplication(sys.argv) window = Window() window.show() sys.exit(App.exec())