0

I have a QDialog with QScrollArea, the QScrollArea has a QLabel containing pixmap. I need to draw on that pixmap. From what I have read in the documentation I should be able to draw directly to the pixmap since the pixmap inherits QPaintDevice. I was not able to do this. The paint event draws nothing and it "erases" the pixmap. What am I doing wrong?

import sys
import PySide6
from PySide6 import QtCore
from PySide6.QtCore import Qt
from PySide6 import QtWidgets
from PIL.ImageQt import ImageQt
from PySide6.QtGui import QPixmap, QPainter, QColor,QBitmap
from PySide6.QtWidgets import QDialog, QVBoxLayout, QLabel, QScrollArea


class MyQLabel(QLabel):
    def __init__(self,originalImage: ImageQt):
        super().__init__()
        self.originalImage = originalImage
        self.pixmap = QPixmap.fromImage(originalImage)
        self.setPixmap(self.pixmap)

    def paintEvent(self, arg__1: PySide6.QtGui.QPaintEvent) -> None:
        painter = QPainter(self.pixmap)
        rect = QtCore.QRect(QtCore.QPoint(0, 0), QtCore.QPoint(30, 30))
        painter.fillRect(rect, QColor("red"))


class MyScrollArea(QScrollArea):
    def __init__(self, originalImage: ImageQt):
        super().__init__()
        self.myQLabel = MyQLabel(originalImage)
        self.setWidget(self.myQLabel)


class MyQDialog(QDialog):
    def __init__(self, img):
        super().__init__()
        self.scrollArea = MyScrollArea(img)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.scrollArea, alignment=Qt.AlignCenter)
        self.setLayout(self.layout)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    image = ImageQt("img.png")
    imageViewer = MyQDialog(image)
    imageViewer.show()
    sys.exit(app.exec())
wajaap
  • 273
  • 3
  • 20
nocturne
  • 627
  • 3
  • 12
  • 39
  • 1
    The `paintEvent` is to draw the widget, why do you want to draw on the pixmap in a paint event handler? – musicamante Feb 17 '22 at 13:54
  • I tried to paint the rectangle in separate method but with no results at all. I managed to paint something in the paint event. – nocturne Feb 17 '22 at 14:09
  • 1
    It's not clear if you *also* want to show the pixmap or you only need to draw on it (maybe to save or use it later). – musicamante Feb 17 '22 at 14:11
  • I need to show to pixmap and then draw on it. No need to save it or use later. – nocturne Feb 17 '22 at 14:20

0 Answers0