简体   繁体   中英

Image not showing while trying to draw a rectangle over a PyQt QLabel

Image does not show up when trying to draw a rectangle over QLabel image. I want to be able to draw a rectangle over the photo and be able to keep the rectangle/hide it. Here's what I tried after checking suggestions here:

from PyQt5.QtGui import QPixmap, QImage, QPainter, QBrush, QColor
from PyQt5.QtWidgets import QMainWindow, QApplication, QDesktopWidget, QVBoxLayout, QWidget, QLabel
from PyQt5.QtCore import QPoint, QRect
import sys
import cv2


class TestRect(QLabel):
    def __init__(self):
        super().__init__()
        self.begin = QPoint()
        self.end = QPoint()

    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()
        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()


class TestWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.current_image = None
        win_rectangle = self.frameGeometry()
        center_point = QDesktopWidget().availableGeometry().center()
        win_rectangle.moveCenter(center_point)
        self.move(win_rectangle.topLeft())
        self.main_layout = QVBoxLayout()
        self.central_widget = QWidget(self)
        self.test_image()
        self.show()

    def test_image(self):
        self.central_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.central_widget)
        image = TestRect()
        self.main_layout.addWidget(image)
        uploaded = cv2.imread('test.jpg')
        resized = cv2.resize(uploaded, (500, 500))
        height, width = 500, 500
        self.current_image = QImage(resized, height, width, QImage.Format_RGB888)
        image.setPixmap(QPixmap(self.current_image))


if __name__ == '__main__':
    test = QApplication(sys.argv)
    test_window = TestWindow()
    sys.exit(test.exec_())

If you override a method without calling the parent's implementation through super then the previous behavior will not be used, and that is what happens in your case: The normal behavior of QLabel is to draw but to override and not to call super it was eliminated . The solution is:

def paintEvent(self, event):
    
    qp = QPainter(self)
    br = QBrush(QColor(100, 10, 10, 40))
    qp.setBrush(br)
    qp.drawRect(QRect(self.begin, self.end))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM