Quantcast
Channel: Active questions tagged qpainter - Stack Overflow
Viewing all articles
Browse latest Browse all 58

How to drag and draw a rectangle over an image in a QLabel? PyQt5 [duplicate]

$
0
0

I have a QLabel that displays a Pixmap and I want the user to be able to drag inside that label and draw a rectangle.

Just like how this code works.

However my label is loaded from a .ui file so I cant just do self.label = MyLabel() in my window class as it'll get rid of my existing label and its styling, I can access my label directly using self.myLabel ("myLabel" being its name in the .ui file). I dont understand how I can subclass my existing label or is it possible to implement this without subclassing?

from PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import *class MyLabel(QLabel):    def __init__(self):        super().__init__()        self.begin = QPoint()        self.end = QPoint()        self.rectangle = None    def paintEvent(self, event):        super().paintEvent(event)        painter = QPainter(self)        painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))        self.rectangle = QRect(self.begin, self.end)        painter.drawRect(self.rectangle)    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.end = event.pos()        self.update()        print((self.rectangle.size()))class MyApp(QMainWindow):    def __init__(self):        super().__init__()        self.label = MyLabel()        self.setCentralWidget(self.label)        self.setGeometry(100, 100, 800, 800)        self.setWindowTitle('Rectangle Drawing')if __name__ == '__main__':    app = QApplication([])    window = MyApp()    window.show()    app.exec_()

Viewing all articles
Browse latest Browse all 58

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>